Spring学习笔记(五)—— Spring整合JDBC
一、Spring对JDBC的支持
Spring提供了很多模板整合Dao技术

与JDBC的整合中,Spring中提供了一个可以操作数据库的对象——JdbcTemplate,该对象封装了JDBC技术,与DBUtils中的QueryRunner非常相似。
二、传统的Jdbc实现
如下为传统的Jdbc实现,该实现有两个明显的缺点就是(1)需要自己管理连接 (2)Jdbc操作重复代码封装与编写
public void save(){
try {
Class.forName("com.mysql.jdbc.Driver");
// 连接对象
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/crm", "root", "root");
// 通过Connection得到Statement对象
Statement stmt = con.createStatement();
// 使用Statement发送sql语句
String sql = "insert into cst_user(user_id,user_name) values(2,'lisi');";
stmt.execute(sql);
// 关闭
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
三、Spring+Jdbc实现
相比于传统的Jdbc实现,在Jdbc API的基础上封装了一套实现JdbcTemplate,JdbcTemplate的优点如下:
(1)配置基于模板设置
(2)完成了资源的创建和释放的工作
(3)完成了对JDBC的核心流程的工作,包括SQL语句的创建和执行,简化了对JDBC的操作
(4)仅需要传递DataSource就可以把它实例化
(5)JdbcTemplate只需要创建一次,减少了代码复用的烦恼
(6)JdbcTemplate是线程安全类
JdbcTemplate的使用步骤如下:
第一步:导包

第二步:书写DAO
- 增删改
// JdbcDaoSupport:根据连接池创建JDBC模板
public class UserDaoImpl extends JdbcDaoSupport implements UserDao { // 增
public void save(User user) {
String sql = "insert into cst_user(user_id,user_name) value(null,?)";
super.getJdbcTemplate().update(sql,user.getName());
} // 删
public void delete(Integer id) {
String sql = "delete from cst_user where user_id=?";
super.getJdbcTemplate().update(sql, id);
} // 改
public void update(User user) {
String sql = "update cst_user set user_name=? where user_id=?";
super.getJdbcTemplate().update(sql, user.getName(),user.getId());
}
} - 查询单个对象
// 查询单个对象
public User getById(Integer id){
String sql = "select * from cst_user where user_id=?";
return super.getJdbcTemplate().queryForObject(sql, new RowMapper<User>(){
@Override
public User mapRow(ResultSet rs, int arg1) throws SQLException {
User user = new User();
user.setId(rs.getInt("user_id"));
user.setName(rs.getString("user_name"));
return user;
}
},id);
} - 查询值类型
// 查询值类型
public int getTotalCount() {
String sql = "select count(*) from cst_user";
Integer count = super.getJdbcTemplate().queryForObject(sql, Integer.class);
return count;
} - 查询list集合类型
// 查询list集合类型
public List<User> getAll() {
String sql = "select * from cst_user";
List<User> list = super.getJdbcTemplate().query(sql, new RowMapper<User>() {
@Override
public User mapRow(ResultSet rs, int arg1) throws SQLException {
User user = new User();
user.setId(rs.getInt("user_id"));
user.setName(rs.getString("user_name"));
return user;
}
});
return list;
}
第三步:准备db.properties
jdbc.jdbcUrl=jdbc:mysql:///crm
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root
第四步:配置applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd "> <!-- 指定spring读取db.properties -->
<context:property-placeholder location="classpath:db.properties"/> <!-- 1.将连接池放入spring容器 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"/>
</bean> <!-- 2.将JDBCTemplate放入spring容器 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean> <!-- 3.将UserDao放入spring容器 -->
<bean id="userDao" class="cn.itcast.dao.impl.UserDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
第五步:测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
@Resource(name="userDao")
private UserDao userDao; @Test
public void fun1() throws Exception {
User user = new User();
user.setName("tom");
userDao.save(user);
}
}
参考资料:https://www.cnblogs.com/jiyukai/p/9386183.html
Spring学习笔记(五)—— Spring整合JDBC的更多相关文章
- Java架构师之路 Spring学习笔记(一) Spring介绍
前言 这是一篇原创的Spring学习笔记.主要记录我学习Spring4.0的过程.本人有四年的Java Web开发经验,最近在面试中遇到面试官总会问一些简单但我不会的Java问题,让我觉得有必要重新审 ...
- spring学习笔记(一) Spring概述
博主Spring学习笔记整理大部分内容来自Spring实战(第四版)这本书. 强烈建议新手购入或者需要电子书的留言. 在学习Spring之前,我们要了解这么几个问题:什么是Spring?Spring ...
- Spring 学习笔记(2) Spring Bean
一.IoC 容器 IoC 容器是 Spring 的核心,Spring 通过 IoC 容器来管理对象的实例化和初始化(这些对象就是 Spring Bean),以及对象从创建到销毁的整个生命周期.也就是管 ...
- Spring学习笔记:Spring整合Mybatis(mybatis-spring.jar)(二:mybatis整合spring)
http://blog.csdn.net/qq598535550/article/details/51703190 二.Spring整合mybatis其实是在mybatis的基础上实现Spring框架 ...
- Spring学习笔记五:Spring进行事务管理
转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6776256.html 事务管理主要负责对持久化方法进行统一的提交或回滚,Spring进行事务管理即我们无需在 ...
- [Spring学习笔记 6 ] Spring JDBC 详解
项目使用maven管理,pom.xml和项目组织如下: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xs ...
- Spring学习笔记:spring整合web之spring-web架包的引用(WebApplicationContextUtils注入容器)
WebApplicationContextUtils 一.Spring整合web之前 案例:给部门列表添加新部门 import org.apache.log4j.Logger; import org. ...
- Spring学习笔记:spring与mybatis四种整合方法
1.采用数据映射器(MapperFactoryBean)的方式,不用写mybatis映射文件,采用注解方式提供相应的sql语句和输入参数. (1)Spring配置文件: <!-- 引入jdbc ...
- Spring学习笔记:Spring整合Mybatis(mybatis-spring.jar)(一:知识点回顾)
一.知识点回顾 1.Mybatis环境搭建(DAO层的实现)(使用maven项目管理工具) 需要引入的依赖包: <!-- 单元测试junit --> <dependency> ...
- Spring学习笔记:Spring整合Mybatis学习PPT(三:整合思路)
三.Spring-Mybatis的整合思路
随机推荐
- 3、python的传入参数
转载:https://blog.csdn.net/abc_12366/article/details/79627263 1.位置参数: def func(a, b): print(a+b) func( ...
- Luogu 4755 Beautiful Pair
分治 + 主席树. 设$solve(l, r)$表示当前处理到$[l, r]$区间的情况,我们可以找到$[l, r]$中最大的一个数的位置$mid$,然后扫一半区间计算一下这个区间的答案. 注意,这时 ...
- csv、txt读写及模式介绍
1读写模式 r以读方式打开文件,可读取文件信息 w已写方式打开文件,可向文件写入信息.如文件存在,则清空,再写入 a以追加模式打开文件,打开文件可指针移至末尾,文件不存在则创建 r+以读写方式打开文件 ...
- 8.python 系统批量运维管理器之pexpect模块
小插曲 前几节讲了paramiko模块,但是pexpect模块的功能几乎跟paramiko一样,先来分析一下: 1.各自介绍 pexpect是一个通过启动子程序,使用正则表达式对程序输出做出特定响应, ...
- [GO]不同作用域的同名变量
package main import "fmt" var a byte //这是一个全局变量 func main() { var a int //这是一个局部变量 //1.作用域 ...
- Python基础入门-For循环
For循环的功能比较强大,他可以帮助我们实现很多重复性的工作.而且for循环能迭代不同的数据结构.他的应用也十分的广泛,作为初学者,我们需要对循环的概念多加理解和练习.接下来我们就来学习for循环的一 ...
- try-catch-finally对返回值的影响
catch 和 finally 一起使用的常见方式是:在 try 块中获取并使用资源,在 catch 块中处理异常情况,并在 finally 块中释放资源. finally 块用于清理try块分配的任 ...
- 正确理解WPF中的TemplatedParent (转贴)
http://blog.csdn.net/idebian/article/details/8761388 (注:Logical Tree中文称为逻辑树,Visual Tree中文称为可视化树或者视觉树 ...
- 15分XX秒后订单自动关闭(倒计时)
//订单记录 function get_order(){ //请求订单ajax方法 XX.send_api("method",{data},function(){ var date ...
- 国外物联网平台(6):Electric Imp
国外物联网平台(6)——Electric Imp 马智 公司背景 Electric Imp成立于2011年,公司设立在美国加利福尼亚州洛斯阿尔托斯和英国剑桥 公司投资者包括:富士康技术集团.PTI创投 ...