前言:
前面有讲过 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的总结就这么多了. (该睡觉了.)

[Spring框架]Spring JDBCTmplate基础入门总结.的更多相关文章

  1. [Spring框架]Spring AOP基础入门总结二:Spring基于AspectJ的AOP的开发.

    前言: 在上一篇中: [Spring框架]Spring AOP基础入门总结一. 中 我们已经知道了一个Spring AOP程序是如何开发的, 在这里呢我们将基于AspectJ来进行AOP 的总结和学习 ...

  2. spring boot集成redis基础入门

    redis 支持持久化数据,不仅支持key-value类型的数据,还拥有list,set,zset,hash等数据结构的存储. 可以进行master-slave模式的数据备份 更多redis相关文档请 ...

  3. Spring框架 - Spring和Spring框架组成

    Spring框架 - Spring和Spring框架组成 Spring是什么?它是怎么诞生的?有哪些主要的组件和核心功能呢? 本文通过这几个问题帮助你构筑Spring和Spring Framework ...

  4. 跟着刚哥学习Spring框架--Spring容器(二)

    Spring容器 启动Spring容器(实例化容器) -- IOC容器读取Bean配置创建Bean实例之前,必须对它进行实例化(加载启动),这样才可以从容器中获取Bean的实例并使用.  Bean是S ...

  5. [Spring框架]Spring AOP基础入门总结一.

    前言:前面已经有两篇文章讲了Spring IOC/DI 以及 使用xml和注解两种方法开发的案例, 下面就来梳理一下Spring的另一核心AOP. 一, 什么是AOP 在软件业,AOP为Aspect ...

  6. Spring框架---Spring入门

    Spring入门 为了能更好的理解先讲一些有的没的的东西: 什么是Spring Spring是分层的JavaSE/EE full-stack(一站式) 轻量级开源框架 分层 SUN提供的EE的三层结构 ...

  7. 深入学习Spring框架(一)- 入门

    1.Spring是什么? Spring是一个JavaEE轻量级的一站式开发框架. JavaEE: 就是用于开发B/S的程序.(企业级) 轻量级:使用最少代码启动框架,然后根据你的需求选择,选择你喜欢的 ...

  8. spring框架的概述与入门

    1. Spring框架的概述 * Spring是一个开源框架 * Spring是于2003 年兴起的一个轻量级的Java开发框架,由Rod Johnson在其著作Expert One-On-One J ...

  9. JavaWeb_(Spring框架)Spring中IoC与DI概念入门

    Spring是于2003 年兴起的一个轻量级的Java 开源框架,它由Rod Johnson创建.传统J2EE应用的开发效率低,Spring作为开源的中间件,提供J2EE应用的各层的解决方案,Spri ...

  10. [Spring框架]Spring开发实例: XML+注解.

    前言: 本文为自己学习Spring记录所用, 文章内容包括Spring的概述已经简单开发, 主要涉及IOC相关知识, 希望能够对新入门Spring的同学有帮助, 也希望大家一起讨论相关的知识. 一. ...

随机推荐

  1. Mysql 分段统计

    今天遇到个小问题觉得挺有意思,与大家分享. 需求是这样的,对数据库中的一张表做按时间的分段统计,结果只要每个区间的数量. select YEAR(create_time) as nian,MONTH( ...

  2. session和cookie的简单理解

    0. 引子,我们为什么要cookie和session       因为http请求是无状态的(不能记录用户的登录状态等),所以需要某种机制来保存用户的登录状态等信息,在下次访问web服务的时候,不用再 ...

  3. [转]redis-cli的一些有趣也很有用的功能

    本文转至:http://www.tuicool.com/articles/Yvqm2ev http://mdba.cn/category/redis/ redis-cli我们最常用的两个参数就是-h. ...

  4. PerconaXtraBackup --全备增备prepare restore

    Xtrabackup Xtrabackup包含两个主要的工具,即xtrabackup和innobackupex,二者区别如下:  • xtrabackup只能备份innodb和xtradb引擎表,而不 ...

  5. gulp-rev-orig

    给客户演示项目时,老是会出现由于缓存,造成的最新的样式或者效果出不来的情况,还得需要手动清除缓存操作,一方面呢,会给客户留下不好的印象,而且也会多了清缓存这一过程,和同事商量过后,决定使用在css或者 ...

  6. 关于 某编译错误: This function or variable may be unsafe. Consider using strcat_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS.

    每次当八月在VS2013里使用strcat的时候,基本上都会出现这个问题╮(╯▽╰)╭ 原因貌似是因为安全问题(⊙o⊙) 于是,解决方法如下: ①更改预处理定义: (这也是八月最常用的方法了,虽然貌似 ...

  7. Software Testing hw1

    I still remember the error which I made in my java project last year. I spent a whole night solving  ...

  8. [置顶]PADS PCB功能使用技巧系列之NO.006- 如何实现OrCAD与PADS Layout同步?

    很多同仁都喜欢用OrCAD画原理图,而PCB Layout则用PADS/PowerPCB,这两者被有些人誉为“黄金组合”,但由于两者并非一套软件,因此如何实现同步亦是需要急待解决的问题... (未完待 ...

  9. FMX下Edit只能输入数字

    procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState) ...

  10. JavaWeb的学习之Servlet(转载自孤傲苍狼)

    一.Servlet简介 Servlet是sun公司提供的一门用于开发动态web资源的技术. Sun公司在其API中提供了一个servlet接口,用户若想用发一个动态web资源(即开发一个Java程序向 ...