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 框架还是 ...
随机推荐
- HGOI20180812 (NOIP2018 提高组 Day1 模拟试题)
前缀数组其实就是有序的,那么答案显然是 我们尝试求出通项公式: 证明如下: 因为 所以: 解之得: 更加通俗的写法如下: 易知 令 那么, (错位相减) 由易知等式代入得, 所以, 所以程 ...
- mysql新版本问题
异常错误:Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.c ...
- Ajax跨域CORS
在Ajax2.0中多了CORS允许我们跨域,但是其中有着几种的限制:Origin.Methods.Headers.Credentials 1.Origin 当浏览器用Ajax跨域请求的时候,会带上一个 ...
- Java基础-赋值运算符Assignment Operators与条件运算符Condition Operators
Java基础-赋值运算符Assignment Operators与条件运算符Condition Operators 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.赋值运算符 表 ...
- Lua程序设计(一)面向对象概念介绍
完整代码 local mt = {} mt.__add = function(t1,t2) print("两个Table 相加的时候会调用我") end local t1 = {} ...
- 干货:制作科研slide简明规范
- .NET面试题系列(四)计算机硬件知识
计算机的硬件组成 总线:贯穿整个系统的是一组电子管道(其实就是传输数据的线路),也就是总线.总线传送的是字,字的大小与系统相关,比如在32位操作系统当中, 一个字是4个字节. I/O设备:I/O设备是 ...
- js异步处理工作机制
js异步处理工作机制 从基础的层面来讲,理解JavaScript的定时器是如何工作的是非常重要的.计时器的执行常常和我们的直观想象不同,那是因为JavaScript引擎是单线程的.我们先来认识一下 ...
- java7,java8 中HashMap和ConcurrentHashMap简介
一:Java7 中的HashMap 结构: HashMap 里面是一个数组,然后数组中每个元素是一个单向链表.链表中每个元素称为一个Entry 实例,Entry 包含四个属性:key, value, ...
- 解决 phpmyadmin #2002 无法登录 MySQL 服务器
将 “phpMyAdmin/libraries”文件夹下的config.default.php文件中的 $cfg['Servers'][$i]['host'] = 'localhost'; 修改为 $ ...