[Spring框架]Spring JDBCTmplate基础入门总结.

前言:
前面有讲过 Spring IOC以及AOP的基本使用方法, 这里就再来讲下Spring JDBCTemplate的使用方法.

一, 概述
这里先说一下Spring 整合的一些模板:

    

从上图中可以看出 Spring为各种支持的持久化技术,都提供了简单操作的模板和回调.

二, 使用JdbcTemplate

2.1 Spring JDBC是Spring提供的持久层技术
简化JDBC API开发,使用上和Apache公司的DBUtils框架非常类似

具体开发使用的jar包结构如图:
    |

2.2, Spring配置连接池
  1, 配置Spring的内置的连接池 

1 <!-- 配置Spring的内置的连接池 -->
2 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
3     <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
4     <property name="url" value="jdbc:mysql:///spring_day02"/>
5     <property name="username" value="root"/>
6     <property name="password" value="123"/>
7 </bean>

  2, 配置DBCP连接池

1 <!-- 配置DBCP连接池 -->
2 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
3     <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
4     <property name="url" value="jdbc:mysql:///spring_day02"/>
5     <property name="username" value="root"/>
6     <property name="password" value="123"/>
7 </bean>

注: 这里如果使用DBCP连接池的话还需要导入Spring 整合DBCP的两个jar包.


  3. C3P0连接池

1 <!-- 配置C3P0连接池 -->
2 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
3     <property name="driverClass" value="com.mysql.jdbc.Driver"/>
4     <property name="jdbcUrl" value="jdbc:mysql:///spring_day02"/>
5     <property name="user" value="root"/>
6     <property name="password" value="123"/>
7 </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的核心配置中引入属性文件: 两种 方式

1 <!-- 引入方式一:引入属性文件 -->
2 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
3     <property name="location" value="classpath:jdbc.properties"/>
4 </bean>
5 <!--引入方式二:引入context的约束-->
6 <context:property-placeholder location="classpath:jdbc.properties"/>

三, 开发案例, 使用Spring JDBCTemplate 进行CRUD操作.

Customer.java:

 1 public class Customer {
 2     private Integer cid;
 3     private String cname;
 4     private Integer age;
 5     public Integer getCid() {
 6         return cid;
 7     }
 8     public void setCid(Integer cid) {
 9         this.cid = cid;
10     }
11     public String getCname() {
12         return cname;
13     }
14     public void setCname(String cname) {
15         this.cname = cname;
16     }
17     public Integer getAge() {
18         return age;
19     }
20     public void setAge(Integer age) {
21         this.age = age;
22     }
23     @Override
24     public String toString() {
25         return "Customer [cid=" + cid + ", cname=" + cname + ", age=" + age
26                 + "]";
27     }
28     
29 }

CustomerDao.java:

 1 /**
 2  * 完成对Customer的CRUD的操作
 3  * 
 4  */
 5 public class CustomerDao extends JdbcDaoSupport {
12 
13     public void save(Customer customer) {
14         this.getJdbcTemplate().update("insert into customer values (null,?,?)",
15                 customer.getCname(), customer.getAge());
16     }
17 
18     public void update(Customer customer) {
19         this.getJdbcTemplate().update(
20                 "update customer set cname = ?,age = ? where cid = ?",
21                 customer.getCname(), customer.getAge(), customer.getCid());
22     }
23 
24     public void delete(Integer cid) {
25         this.getJdbcTemplate()
26                 .update("delete from customer where cid = ?", cid);
27     }
28 
29     public Integer findCount() {
30         int count = this.getJdbcTemplate().queryForInt(
31                 "select count(*) from customer");
32         return count;
33     }
34 
35     public String findNameById(Integer cid) {
36         String cname = this.getJdbcTemplate().queryForObject(
37                 "select cname from customer where cid = ?", String.class, cid);
38         return cname;
39     }
40 
41     public Customer findById(Integer cid) {
42         Customer customer = this.getJdbcTemplate().queryForObject(
43                 "select * from customer where cid = ?",
44                 new BeanPropertyRowMapper<Customer>(Customer.class), cid);
45         return customer;
46     }
47 
48     public List<Customer> findAll() {
49         List<Customer> list = this.getJdbcTemplate().query("select * from customer",
50                 new BeanPropertyRowMapper<Customer>(Customer.class));
51         return list;
52     }
53 }

SpringDemo2.java 测试类:

 1 @RunWith(SpringJUnit4ClassRunner.class)
 2 @ContextConfiguration("classpath:applicationContext2.xml")
 3 public class SpringDemo2 {
 4 
 5     @Resource(name="customerDao")
 6     private CustomerDao customerDao;
 7     
 8     @Test
 9     public void demo1(){
10         
11         Customer customer = new Customer();
12         customer.setCname("马大帅");
13         customer.setAge(48);
14         
15         customerDao.save(customer);
16     }
17     
18     @Test
19     public void demo2(){
20         
21         Customer customer = new Customer();
22         customer.setCid(8);
23         customer.setCname("马小帅");
24         customer.setAge(38);
25         
26         customerDao.update(customer);
27     }
28     
29     @Test
30     public void demo3(){
31         customerDao.delete(7);
32     }
33     
34     @Test
35     public void demo4(){
36         int count = customerDao.findCount();
37         System.out.println(count);
38     }
39     
40     @Test
41     public void demo5(){
42         String cname = customerDao.findNameById(8);
43         System.out.println(cname);
44     }
45     
46     @Test
47     public void demo6(){
48         Customer customer = customerDao.findById(8);
49         System.out.println(customer);
50     }
51     
52     @Test
53     public void demo7(){
54         List<Customer> customers = customerDao.findAll();
55         for (Customer customer : customers) {
56             System.out.println(customer);
57         }
58     }
59 }

applicationContext.xml 配置文件:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xsi:schemaLocation="
 6 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 7 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 8     
 9     
10     <context:property-placeholder location="classpath:jdbc.properties"/>
11     
12     <!-- 配置C3P0连接池 -->
13     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
14         <property name="driverClass" value="${jdbc.driverClass}"/>
15         <property name="jdbcUrl" value="${jdbc.url}"/>
16         <property name="user" value="${jdbc.user}"/>
17         <property name="password" value="${jdbc.password}"/>
18     </bean>
19     
20     
21     <!-- 配置DAO -->
22     <bean id="customerDao" class="cn.itcast.jdbc.demo2.CustomerDao">
23         <property name="dataSource" ref="dataSource"/>
24     </bean>
25 </beans>


好了, 一个基本的CRUD操作就完成了, 在这里我们可以发现配置文件特别的简洁, 我们只是给customerDao注入了一个dataSource , 然后在CustomerDao.java中就可以用this.getJdbcTemplate()获取到JDBCTemplate的实例了, 这个原理是因为我们的CustomerDao继承了 JdbcDaoSupport , 这里我们就来看下它的源码:

首先我们使用this.getJdbcTemplate而获取到一个jdbcTemplate实例:

1 /**
2  * Return the JdbcTemplate for this DAO,
3  * pre-initialized with the DataSource or set explicitly.
4  */
5 public final JdbcTemplate getJdbcTemplate() {
6   return this.jdbcTemplate;
7 }

那么又返回的这个this.jdbcTemplate是否是有值得呢?  再看源代码原来是在我们setDataSource的时候生成了jdbcTemplate实例.

1 /**
2  * Set the JDBC DataSource to be used by this DAO.
3  */
4 public final void setDataSource(DataSource dataSource) {
5     if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) {
6         this.jdbcTemplate = createJdbcTemplate(dataSource);
7         initTemplateConfig();
8     }
9 }

 

好了, 到了这里就没有了, 关于JDBCTemplate的总结就这么多了. (该睡觉了.)

posted @ 2016-07-05 23:22  一枝花算不算浪漫  阅读(1940)  评论(0编辑  收藏  举报