Spring之JDBCTemplate学习
一、Spring对不同的持久化支持:
Spring为各种支持的持久化技术,都提供了简单操作的模板和回调
| ORM持久化技术 | 模板类 |
| JDBC | org.springframework.jdbc.core.JdbcTemplate |
| Hibernate5.0 | org.springframework.orm.hibernate5.HibernateTemplate |
| IBatis(MyBatis) | org.springframework.orm.ibatis.SqlMapClientTemplate |
| JPA | org.springfrmaework.orm.jpa.JpaTemplate |
其实Spring的JDBCTemplate有点像DBUtils,但是有时候还没有DBUitls好用。这里来学习一下使用Spring的JDBCTemplate来玩一下CRUD。
二、使用JdbcTemplate需要的jar包
在这里使用Spring的JDBCTemplate的时候先要把轮子拿过来:

除此之外,在Java中操作数据库怎么能不要对应的驱动包呢:

三、JdbcTemplate使用的基本步骤
然后再看看Spring的JDBCTemplate的使用大体步骤,这里有一个小例子:
package com.spring.test; import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource; public class TestJDBCTemplate { @Test
public void test1() { // JDBC模板依赖于连接池来获得数据的连接,所以必须先要构造连接池
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/spring");
dataSource.setUsername("root");
dataSource.setPassword(""); // 创建JDBC模板
JdbcTemplate jdbcTemplate = new JdbcTemplate();
// 这里也可以使用构造方法
jdbcTemplate.setDataSource(dataSource); // sql语句
String sql = "select count(*) from user";
Long num = (long) jdbcTemplate.queryForObject(sql, Long.class); System.out.println(num); } }
四、进一步的考虑
其实这个例子本身没有什么的,只是演示了一下,其实在学Spring之后,感觉应该形成一种习惯,在new对象的时候我要想到IOC,在使用Set方法的时候,我要想到DI,再去要方便面(哦,不,是切面),我们应该想到用AOP的。这里可以在Spring中配置如下的引用链:
1. 我要有DataSource,DataSource的属性可以通过注入数据库的一些配置属性添加
2. 我要有JdbcTemplate,而Template依赖与DataSource,我要以ref的方式为我的JdbcTemplate注入引用
3. 有了JdbcTemplate之后,我要有Dao,此时我应该在Dao添加一个JdbcTemplate的成员,然后以ref的方式将JdbcTemplate引入到Dao中
4. 我在Action或者是Servlet中都会调用的是Serivce,所以,我在Serivce中要添加一个Dao作为成员,然后由ref在注入Dao到Service中
DataSource --> JdbcTemplate --> Dao --> Service --> Action/Servlet
"-->"表示将左边的对象注入到右边的对象当中
配置文件如下:
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- IOC和DI的注解扫描 -->
<context:component-scan base-package="com.spring" ></context:component-scan> <!-- 打开AOP的注解 -->
<!-- 这里用的是中间的横线而不是下划线 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring_03"></property>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean> <bean id="userDao" class="com.spring.dao.UserDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean> <bean id="userService" class="com.spring.service.UserService">
<property name="userDao" ref="userDao"></property>
</bean> </beans>
其中dataSource和jdbcTemplate都是直接配置的,不用写啥。
然后是UserDao.java
package com.spring.dao;
import org.springframework.jdbc.core.JdbcTemplate;
import com.spring.domain.User;
public class UserDao {
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void addUser(User user) {
String sql = "insert into user (username, password) values (?, ?)";
jdbcTemplate.update(sql, user.getUsername(), user.getPassword());
}
}
UserSerice.java
package com.spring.service; import com.spring.dao.UserDao;
import com.spring.domain.User; public class UserService { // 加入userDao作为成员变变量
private UserDao userDao; // 注意这里要增加get和set方法
public UserDao getUserDao() {
return userDao;
} public void setUserDao(UserDao userDao) {
this.userDao = userDao;
} public void addUser(User user) {
userDao.addUser(user);
}
}
上面的文件都是用的配置文件来获得对象的,而没有使用注解。
测试类:
package com.spring.test; import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.domain.User;
import com.spring.service.UserService; public class TestJDBCTemplate { @Test
public void test2() { ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
UserService userService = (UserService) ctx.getBean("userService"); User user = new User();
user.setPassword("");
user.setUsername("小王"); userService.addUser(user); } }
哦,对了其中配置的数据源是C3P0的数据源,还要导入C3P0的包:

五、JdbcTemplate的CRUD方法
1. 插入数据
public void addUser(User user) {
String sql = "insert into user (username, password) values (?, ?)";
jdbcTemplate.update(sql, user.getUsername(), user.getPassword());
}
如上,插入代码用的是update方法,其实增删改用的都是update方法,而查询则是和query相关的方法。
2. 删除操作
public void deleteUser( ) {
String sql = "delete from user where username= ?";
jdbcTemplate.update(sql, "小王");
}
3. 修改操作
public void updateUser(User user) {
String sql = "update user set username=? where username= ?";
jdbcTemplate.update(sql, user.getUsername() + "_new", user.getUsername());
}
4. 查询操作
上面三个都比较简单,查询倒是有些复杂。在使用比较基础的持久化工具的时候,比如DBUtils都会针对查询结果给我们提供一些封装的接口和类,但是JdbcTemplate只给我们提供了接口,并没有可用的类,所以我们需要自己写实现类来进行封装。这里会学习使用JdbcTemplate进行三种查询操作:
4.a. 查询表的记录数

@Test
public void test5() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
String sql = "select count(*) from user";
Long row = jdbcTemplate.queryForObject(sql, Long.class);
System.out.println("查询出来的记录数为:" + row);
}
4.b. 查询返回对象

@Test
public void test6() {
// 获得jdbcTemplate对象
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
String sql = "select username, password from user where username = ?";
// 设定参数
Object[] object = {"mary_new"};
// 进行查询
User user = jdbcTemplate.queryForObject(sql, object, new UserMapper());
System.out.println(user);
}
除此之外要实现结构RowMapper来新建一个映射类:
package com.spring.test; import java.sql.ResultSet;
import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import com.spring.domain.User; public class UserMapper implements RowMapper<User>{ @Override
public User mapRow(ResultSet resultSet, int rows) throws SQLException {
User user = new User();
user.setUsername(resultSet.getString(1));
user.setPassword(resultSet.getString(2)); return user;
} }
要注意这个UserMapper.java应该要和具体的Sql语句对应。
4.c. 查询并返回List集合

@Test
public void test7() {
// 获得jdbcTemplate对象
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate"); // sql语句
String sql = "select * from user";
List<User> users = jdbcTemplate.query(sql, new UserMapper()); for(User u: users) {
System.out.println(u);
}
}
总结:
1. Spring全套管理各种组件,注入、控制反转等,将组件之间的关系以配置文件的形式串联起来,最大程度的对应用解耦和
2. Spring的JdbcTemplate中的CRUD操作还好,比较常规,但是也只对JDBC的持久化操作的演示,还没用其他的呢
3. 多练习下配置文件编写,注入的方式、写法还不是很熟
Spring之JDBCTemplate学习的更多相关文章
- spring 学习(四): spring 的 jdbcTemplate 操作
spring 学习(四): spring 的 jdbcTemplate 操作 spring 针对 javaee 的每一层,都提供了相应的解决技术,jdbcTemplate 的主要操作在 dao 层. ...
- spring学习(四)spring的jdbcTemplate(增删改查封装)
Spring的jdbcTemplate操作 1.Spring框架一站式框架 (1)针对javaee三层,每一层都有解决技术 (2)到dao 层,使用 jdbcTemplate 2.Spring对不同的 ...
- JdbcTemplate学习笔记
JdbcTemplate学习笔记 1.使用JdbcTemplate的execute()方法执行SQL语句 Java 代码 jdbcTemplate.execute("CREATE TABLE ...
- 框架源码系列十一:事务管理(Spring事务管理的特点、事务概念学习、Spring事务使用学习、Spring事务管理API学习、Spring事务源码学习)
一.Spring事务管理的特点 Spring框架为事务管理提供一套统一的抽象,带来的好处有:1. 跨不同事务API的统一的编程模型,无论你使用的是jdbc.jta.jpa.hibernate.2. 支 ...
- spring+spring mvc+JdbcTemplate 入门小例子
大家使用这个入门时候 最好能够去 搜一下 spring mvc 的 原理,我放一张图到这里,自己琢磨下,后面去学习就容易了 给个链接 (网上一把,千万不能懒) https://www.cnblo ...
- spring HttpInvoker相关学习资料
官方文档 spring支持的几种RPC 用Http Invoker实现RCP客户端与后台的交互 Java HttpInvoker小试 Spring注解发布RMI/HTTPInvoker/Hessian ...
- Spring利用JDBCTemplate实现批量插入和返回id
1.先介绍一下java.sql.Connection接口提供的三个在执行插入语句后可取的自动生成的主键的方法: //第一个是 PreparedStatement prepareStatement(St ...
- spring源码学习之路---深入AOP(终)
作者:zuoxiaolong8810(左潇龙),转载请注明出处,特别说明:本博文来自博主原博客,为保证新博客中博文的完整性,特复制到此留存,如需转载请注明新博客地址即可. 上一章和各位一起看了一下sp ...
- spring源码学习之路---IOC初探(二)
作者:zuoxiaolong8810(左潇龙),转载请注明出处,特别说明:本博文来自博主原博客,为保证新博客中博文的完整性,特复制到此留存,如需转载请注明新博客地址即可. 上一章当中我没有提及具体的搭 ...
随机推荐
- day12-13 文件操作b模式
为什么需要用到二进制的形式?我们默认的r w a 其实是rt wt at 即txt模式如果是图片,视频,音频,是无法用txt打开的,只能用b模式处理 b 模式是以字节形式打开 f = open(&qu ...
- 学习 Spring Boot:(二十九)Spring Boot Junit 单元测试
前言 JUnit 是一个回归测试框架,被开发者用于实施对应用程序的单元测试,加快程序编制速度,同时提高编码的质量. JUnit 测试框架具有以下重要特性: 测试工具 测试套件 测试运行器 测试分类 了 ...
- 【BZOJ2426】[HAOI2010]工厂选址(贪心)
[BZOJ2426][HAOI2010]工厂选址(贪心) 题面 BZOJ 洛谷 题解 首先看懂题目到底在做什么. 然而发现我们显然可以对于每个备选位置跑一遍费用流,然后并不够优秀. 不难发现所有的位置 ...
- SDL_BlitSurface
SDL_BlitSurface Use this function to perform a fast surface copy to a destination surface. Contents ...
- Libre 6012 「网络流 24 题」分配问题 (网络流,费用流)
Libre 6012 「网络流 24 题」分配问题 (网络流,费用流) Description 有n件工作要分配给n个人做.第i个人做第j件工作产生的效益为\(c_{ij}\).试设计一个将n件工作分 ...
- 「THUPC2018」赛艇 / Citing
https://loj.ac/problem/6388 矩形匹配,小地图经过位置为1,和大地图匹配不能同时存在一个1的位置,就可以是一个当前位置 1.bitset压位,....O(n^2m^2/64) ...
- [FJOI2017]矩阵填数——容斥
参考:题解 P3813 [[FJOI2017]矩阵填数] 题目大意: 给定一个 h∗w 的矩阵,矩阵的行编号从上到下依次为 1...h ,列编号从左到右依次 1...w . 在这个矩阵中你需要在每个格 ...
- qbxt的题:找一个三元环
有向图中找一个三元环 题意: 考虑 N 个人玩一个游戏, 任意两个人之间进行一场游戏 (共 N*(N-1)/2 场),且每场一定能分出胜负.现在,你需要在其中找到三个人构成的这样的局面:A战胜B,B战 ...
- 解决invalid record found in VCF4 file (at least 8 tab-delimited fields expected)问题,批量修改空格改为制表格格式
出现这种问题说明一般存在两个问题: 第一,vcf文件不足8个分割制表符,比如像如下文件: 为了解决这个问题,说明在做snp filter时候,需要提取至少8个制表符的字符串,比如,像如下文件所示: 第 ...
- vue router.push(),router.replace(),router.go()
1.router.push(location)=====window.history.pushState 想要导航到不同的 URL,则使用 router.push 方法.这个方法会向 history ...