前言:
前面有讲过 Spring IOC以及AOP的基本使用方法, 这里就再来讲下Spring JDBCTemplate的使用方法.
一, 概述
这里先说一下Spring 整合的一些模板:
从上图中可以看出 Spring为各种支持的持久化技术,都提供了简单操作的模板和回调.
二, 使用JdbcTemplate
2.1 Spring JDBC是Spring提供的持久层技术
简化JDBC API开发,使用上和Apache公司的DBUtils框架非常类似
具体开发使用的jar包结构如图:
|
2.2, Spring配置连接池
1, 配置Spring的内置的连接池
<!-- 配置Spring的内置的连接池 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///spring_day02"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</bean>
2, 配置DBCP连接池
<!-- 配置DBCP连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///spring_day02"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</bean>
注: 这里如果使用DBCP连接池的话还需要导入Spring 整合DBCP的两个jar包.
3. C3P0连接池
<!-- 配置C3P0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql:///spring_day02"/>
<property name="user" value="root"/>
<property name="password" value="123"/>
</bean>
4,引入属性文件: 写jdbc.properties 文件, 然后直接将配置文件注入到Spring中
jdbc.properties 配置文件:
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_day02
jdbc.user=root
jdbc.password=123
在Spring的核心配置中引入属性文件: 两种 方式
<!-- 引入方式一:引入属性文件 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties"/>
</bean>
<!--引入方式二:引入context的约束-->
<context:property-placeholder location="classpath:jdbc.properties"/>
三, 开发案例, 使用Spring JDBCTemplate 进行CRUD操作.
Customer.java:
public class Customer {
private Integer cid;
private String cname;
private Integer age;
public Integer getCid() {
return cid;
}
public void setCid(Integer cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Customer [cid=" + cid + ", cname=" + cname + ", age=" + age
+ "]";
} }
CustomerDao.java:
/**
* 完成对Customer的CRUD的操作
*
*/
public class CustomerDao extends JdbcDaoSupport { public void save(Customer customer) {
this.getJdbcTemplate().update("insert into customer values (null,?,?)",
customer.getCname(), customer.getAge());
} public void update(Customer customer) {
this.getJdbcTemplate().update(
"update customer set cname = ?,age = ? where cid = ?",
customer.getCname(), customer.getAge(), customer.getCid());
} public void delete(Integer cid) {
this.getJdbcTemplate()
.update("delete from customer where cid = ?", cid);
} public Integer findCount() {
int count = this.getJdbcTemplate().queryForInt(
"select count(*) from customer");
return count;
} public String findNameById(Integer cid) {
String cname = this.getJdbcTemplate().queryForObject(
"select cname from customer where cid = ?", String.class, cid);
return cname;
} public Customer findById(Integer cid) {
Customer customer = this.getJdbcTemplate().queryForObject(
"select * from customer where cid = ?",
new BeanPropertyRowMapper<Customer>(Customer.class), cid);
return customer;
} public List<Customer> findAll() {
List<Customer> list = this.getJdbcTemplate().query("select * from customer",
new BeanPropertyRowMapper<Customer>(Customer.class));
return list;
}
}
SpringDemo2.java 测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext2.xml")
public class SpringDemo2 { @Resource(name="customerDao")
private CustomerDao customerDao; @Test
public void demo1(){ Customer customer = new Customer();
customer.setCname("马大帅");
customer.setAge(48); customerDao.save(customer);
} @Test
public void demo2(){ Customer customer = new Customer();
customer.setCid(8);
customer.setCname("马小帅");
customer.setAge(38); customerDao.update(customer);
} @Test
public void demo3(){
customerDao.delete(7);
} @Test
public void demo4(){
int count = customerDao.findCount();
System.out.println(count);
} @Test
public void demo5(){
String cname = customerDao.findNameById(8);
System.out.println(cname);
} @Test
public void demo6(){
Customer customer = customerDao.findById(8);
System.out.println(customer);
} @Test
public void demo7(){
List<Customer> customers = customerDao.findAll();
for (Customer customer : customers) {
System.out.println(customer);
}
}
}
applicationContext.xml 配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 配置C3P0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean> <!-- 配置DAO -->
<bean id="customerDao" class="cn.itcast.jdbc.demo2.CustomerDao">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
好了, 一个基本的CRUD操作就完成了, 在这里我们可以发现配置文件特别的简洁, 我们只是给customerDao注入了一个dataSource , 然后在CustomerDao.java中就可以用this.getJdbcTemplate()获取到JDBCTemplate的实例了, 这个原理是因为我们的CustomerDao继承了 JdbcDaoSupport , 这里我们就来看下它的源码:
首先我们使用this.getJdbcTemplate而获取到一个jdbcTemplate实例:
/**
* Return the JdbcTemplate for this DAO,
* pre-initialized with the DataSource or set explicitly.
*/
public final JdbcTemplate getJdbcTemplate() {
return this.jdbcTemplate;
}
那么又返回的这个this.jdbcTemplate是否是有值得呢? 再看源代码原来是在我们setDataSource的时候生成了jdbcTemplate实例.
/**
* Set the JDBC DataSource to be used by this DAO.
*/
public final void setDataSource(DataSource dataSource) {
if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) {
this.jdbcTemplate = createJdbcTemplate(dataSource);
initTemplateConfig();
}
}
好了, 到了这里就没有了, 关于JDBCTemplate的总结就这么多了. (该睡觉了.)