ref:Spring JdbcTemplate+JdbcDaoSupport实例
ref:https://www.yiibai.com/spring/spring-jdbctemplate-jdbcdaosupport-examples.html
1. 不使用JdbcTemplate示例:如果不用JdbcTemplate,必须创建大量的冗余代码(创建连接,关闭连接,处理异常)中的所有DAO数据库的操作方法 - 插入,更新和删除。它的效率并不是很高,容易出错和乏味。
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, customer.getCustId());
2. 使用JdbcTemplate示例:使用JdbcTemplate可节省大量的冗余代码,因为JdbcTemplate类会自动处理它。
private DataSource dataSource;
private JdbcTemplate jdbcTemplate; public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
} public void insert(Customer customer){ String sql = "INSERT INTO CUSTOMER " +
"(CUST_ID, NAME, AGE) VALUES (?, ?, ?)"; jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.update(sql, new Object[] { customer.getCustId(),
customer.getName(),customer.getAge()
}); }
3. 使用JdbcDaoSupport示例通过扩展 JdbcDaoSupport,设置数据源,并且 JdbcTemplate 在你的类中不再是必需的,只需要正确的数据源注入JdbcCustomerDAO。可以使用 getJdbcTemplate()方法得到 JdbcTemplate。
customerDAO类函数:
public class JdbcCustomerDAO extends JdbcDaoSupport implements CustomerDAO
{
//no need to set datasource here
public void insert(Customer customer){
String sql = "INSERT INTO CUSTOMER " +
"(CUST_ID, NAME, AGE) VALUES (?, ?, ?)";
customer.setName("test',2);show databases;#");//无法注入!spring自动将'进行转义。即使为test\',2)也无法注入。
getJdbcTemplate().update(sql, new Object[] { customer.getCustId(),customer.getName(),customer.getAge() }); }//此处将
4.相应的xml文件设置dataSource/customerDAO
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/yiibaijava" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean> </beans>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="customerDAO" class="com.yiibai.customer.dao.impl.JdbcCustomerDAO">
<property name="dataSource" ref="dataSource" />
</bean> </beans>
public String findCustomerNameById(int custId){
String sql = "SELECT NAME FROM CUSTOMER WHERE CUST_ID = ?";
String name = (String)getJdbcTemplate().queryForObject(
sql, new Object[] { custId }, String.class);
return name;
}//此处查询条件为int custID,显然php中整数型注入无法应用。
字符串查询情况:
public Customer findByCustomerName(String name){
String sql = "SELECT * FROM CUSTOMER WHERE NAME = ?";
name="name1';show databases;#";//spring直接转义'name1\';show databases;#'。无法注入!
Customer customer = (Customer)getJdbcTemplate().queryForObject(
sql, new Object[] { name }, new CustomerRowMapper());
return customer;
}
与php不同,java中对象为强类型,int无法注入,而字符串又直接转义,避免了注入的可能性。
public Customer findByCustomerId(int custId){ String sql = "SELECT * FROM CUSTOMER WHERE CUST_ID = ?"; Customer customer = (Customer)getJdbcTemplate().queryForObject(
sql, new Object[] { custId }, new CustomerRowMapper()); return customer;
} public class CustomerRowMapper implements RowMapper
{
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Customer customer = new Customer();
customer.setCustId(rs.getInt("CUST_ID"));
customer.setName(rs.getString("NAME"));
customer.setAge(rs.getInt("AGE"));
return customer;
}
}
为了解决这个问题,可以使用“命名参数”,SQL参数是由一个冒号开始后续定义的名称,而不是位置。在另外的,命名参数只是在SimpleJdbcTemplate类和NamedParameterJdbcTemplate支持。
例子向您展示如何使用命名参数在一个 INSERT 语句。
//insert with named parameter
public void insertNamedParameter(Customer customer){ String sql = "INSERT INTO CUSTOMER " +
"(CUST_ID, NAME, AGE) VALUES (:custId, :name, :age)"; Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("custId", customer.getCustId());
parameters.put("name", customer.getName());
parameters.put("age", customer.getAge()); getSimpleJdbcTemplate().update(sql, parameters); }
示例 2 例子来说明如何使用命名参数在批处理操作语句。
public void insertBatchNamedParameter(final List<Customer> customers){ String sql = "INSERT INTO CUSTOMER " +
"(CUST_ID, NAME, AGE) VALUES (:custId, :name, :age)"; List<SqlParameterSource> parameters = new ArrayList<SqlParameterSource>();
for (Customer cust : customers) {
parameters.add(new BeanPropertySqlParameterSource(cust));
} getSimpleJdbcTemplate().batchUpdate(sql,
parameters.toArray(new SqlParameterSource[0]));
}
8.spring web中xml配置jdbctemplate.
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/abc" />
<property name="resourceRef" value="true"/>
</bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean> <resource-ref>
<res-ref-name>
jdbc/abc
</res-ref-name>
<res-type>
javax.sql.DataSource
</res-type>
</resource-ref> tomcat/conf/context.xml:
<Resource name="jdbc/abc" auth="Container" type="javax.sql.DataSource"
...
</Resource >
9.getSimpleJdbcTemplate执行多行sql语句问题
在默认情况下,即datasource设置为"jdbc:mysql://192.168.0.10:3306/yiibai”,不能执行多行sql语句,将会产生错误:PreparedStatementCallback; bad SQL grammar。
若要执行多行语句,设置datasource为“jdbc:mysql://192.168.0.10:3306/yiibai?allowMultiQueries=true”,则可以顺利执行。
ref:Spring JdbcTemplate+JdbcDaoSupport实例的更多相关文章
- Spring JdbcTemplate+JdbcDaoSupport实例
在Spring JDBC开发中,可以使用 JdbcTemplate 和 JdbcDaoSupport 类来简化整个数据库的操作过程. 在本教程中,我们将重复上一篇文章Spring+JDBC例子,看之前 ...
- Spring JdbcTemplate+JdbcDaoSupport实例(和比较)
首先,数据库是这样的,很简单. 当然,要引入spring的包,这里我全部导入了,省事. applicationContext.xml是这样的: <?xml version="1.0&q ...
- Spring + JdbcTemplate + JdbcDaoSupport examples
In Spring JDBC development, you can use JdbcTemplate and JdbcDaoSupport classes to simplify the over ...
- Spring JdbcTemplate batchUpdate() 实例
在某些情况下,可能需要将一批记录插入到数据库中.如果你对每条记录调用一个插件的方法,SQL语句将被重复编译,造成系统缓慢进行. 在上述情况下,你可以使用 JdbcTemplate BATCHUPDAT ...
- Spring JdbcTemplate查询实例
这里有几个例子向您展示如何使用JdbcTemplate的query()方法来查询或从数据库提取数据.整个项目的目录结构如下: 1.查询单行数据 这里有两种方法来查询或从数据库中提取单行记录,并将其转换 ...
- 【Spring】Spring的数据库开发 - 1、Spring JDBC的配置和Spring JdbcTemplate的解析
Spring JDBC 文章目录 Spring JDBC Spring JdbcTemplate的解析 Spring JDBC的配置 简单记录-Java EE企业级应用开发教程(Spring+Spri ...
- 使用Spring JDBCTemplate简化JDBC的操作
使用Spring JDBCTemplate简化JDBC的操作 接触过JAVA WEB开发的朋友肯定都知道Hibernate框架,虽然不否定它的强大之处,但个人对它一直无感,总感觉不够灵活,太过臃肿了. ...
- JAVA入门[18]-JdbcTemplate简单实例
一.关于JdbcTemplate JdbcTemplate是最基本的Spring JDBC模板,这个模板支持简单的JDBC数据库访问功能以及基于索引参数的查询. Spring数据访问模板:在数据库操作 ...
- Spring MVC框架实例
Spring MVC 背景介绍 Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块.使用 Spring 可插入的 MVC 架构,能够选择是使用内置的 Spring Web 框架还是 ...
随机推荐
- 【洛谷P1272】道路重建
题目大意:给定一个 N 个节点的树,求至少剪掉多少条边才能使得从树中分离出一个大小为 M 的子树. 题解:考虑树形 dp,定义 \(dp[u][i][t]\) 为以 u 为根节点与前 i 个子节点构成 ...
- 洛谷P3862 8月月赛B
https://www.luogu.org/problemnew/show/P3862#sub P3862 8月月赛B 推公式:f(n)->f(n+1) 奇葩的预处理 https://www.l ...
- Redis记录-Redis高级应用
Redis数据库可以使用安全的方案,使得进行连接的任何客户端在执行命令之前都需要进行身份验证.要保护Redis安全,需要在配置文件中设置密码. 示例 下面的示例显示了保护Redis实例的步骤. 127 ...
- js实现表单提交submit(),onsubmit
通常表单的提交有两种方式,一是直接通过html的form提交,代码如下: <form action="" method="" id="forms ...
- bzoj千题计划225:bzoj2143: 飞飞侠
http://www.lydsy.com/JudgeOnline/problem.php?id=2143 分层图最短路 把能够弹跳的曼哈顿距离看做能量 dp[i][j][k]表示在(i,j)位置,还有 ...
- ngx_lua_API 指令详解(二)ngx.re.match/find/gmatch/sub/gsub指令集合
1.先来个官方的ngx.re.match location /ngx_re_match { default_type text/html; content_by_lua_block { local m ...
- html5 canvas 奇怪的形状垂直渐变
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- unp学习笔记——Chapter1
1.发现网络拓扑的几个重要的命令 (1).netstat -i 提供网络接口的信息.我们还指定-n 标志以输出数值地址,而不是试图把它们反向解析成名字.netstat -r 展示路由表. dzhwen ...
- javascritpt创建对象
javascript添加对象示例: <script> person=new Object(); person.firstname="Bill"; person.last ...
- 小程序登录、微信网页授权(Java版)
首先呢,“登录”.“授权”.“授权登录”,是一样的意思,不用纠结. 写小程序授权登录的代码前,需要了解清楚openid与unionid的区别,这里再简单介绍一下: 腾讯有个 “微信·开放平台”,只有企 ...