SSM框架之Spring(5)JdbcTemplate及spring事务控制
Spring(5)JdbcTemplate及spring事务控制
##1、JdbcTmeplate
它是 spring 框架中提供的一个对象,是对原始 Jdbc API 对象的简单封装。spring 框架为我们提供了很多的操作模板类。
操作关系型数据的:
JdbcTemplate
HibernateTemplate
操作 nosql 数据库的:
RedisTemplate
操作消息队列的:
JmsTemplate
我们今天的主角在 spring-jdbc-5.0.2.RELEASE.jar 中,我们在导包的时候,除了要导入这个 jar 包外,还需要导入一个 spring-tx-5.0.2.RELEASE.jar(它是和事务相关的)。
1.1、JdbcTemplate 对象的创建
我们可以参考它的源码,来一探究竟:
public JdbcTemplate() {
}
public JdbcTemplate(DataSource dataSource) {
setDataSource(dataSource);
afterPropertiesSet();
}
public JdbcTemplate(DataSource dataSource, boolean lazyInit) {
setDataSource(dataSource);
setLazyInit(lazyInit);
afterPropertiesSet();
}
除了默认构造函数之外,都需要提供一个数据源。既然有set方法,依据我们之前学过的依赖注入,我们可以在配置文件中配置这些对象。
1.1.1、通过代码配置
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
public class JdbcTemplateDemo1 {
public static void main(String[] args) {
//使用spring自己提供的数据源创建
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql:///spring");
ds.setUsername("root");
ds.setPassword("123456");
JdbcTemplate jt = new JdbcTemplate();
jt.setDataSource(ds);
jt.execute("insert into account(name,money) values ('ccc',111111)");
}
}
这样配置安全性低,所有在正式使用时,不会采用这种方式,而是采用xml配置
1.1.2、通过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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--spring框架也提供了一个内置数据源我们也可以使用spring的内置数据源,它就在spring-jdbc-5.0.2.REEASE.jar包中-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///spring"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--配置账户持久层-->
<bean id="accountDao" class="wf.dao.impl.AccountImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
</beans>
1.2、JdbcTemplate的CRUD操作
JdbcTemplate的增删改操作都由updata方法及其重载操作实现
1.2.1、插入操作
public class JdbcTemplateDemo2 {
public static void main(String[] args) {
//1.获取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 id 获取 bean 对象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.执行操作
jt.execute("insert into account(name,money)values('eee',500)");
}
}
1.2.2、更新操作
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 id 获取 bean 对象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.执行操作
//修改
jt.update("update account set money = money-? where id = ?",300,6);
}
}
1.2.3、删除操作
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 id 获取 bean 对象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.执行操作
//删除
jt.update("delete from account where id = ?",6);
}
}
1.2.4、 查询操作
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 id 获取 bean 对象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.执行操作
//查询所有
List<Account> accounts = jt.query("select * from account where money > ? ",
new AccountRowMapper(), 500);
for(Account o : accounts){
System.out.println(o);
}
}
}
public class AccountRowMapper implements RowMapper<Account>{
@Override
public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
Account account = new Account();
account.setId(rs.getInt("id"));
account.setName(rs.getString("name"));
account.setMoney(rs.getFloat("money"));
return account;
}
}
======================================================================================
使用 RowMapper 的方式:常用的方式
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 id 获取 bean 对象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.执行操作
//查询一个
List<Account> as = jt.query("select * from account where id = ? ",
new AccountRowMapper(), 55);
System.out.println(as.isEmpty()?"没有结果":as.get(0));
}
}
用 使用 ResultSetExtractor 的方式: 不常用的方式
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 id 获取 bean 对象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.执行操作
//查询一个
Account account = jt.query("select * from account where id = ?",
new AccountResultSetExtractor(),3);
System.out.println(account);
}
}
1.3、dao中使用JdbcTemplate
//实体类
import java.io.Serializable;
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
===============================================================================
import wf.domain.Account;
public interface AccountDao {
Account slelctAccountById(Integer id);
Account selectAccountByName(String name);
void updateAccount(Account account);
}
=================================================================================
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import wf.dao.AccountDao;
import wf.domain.Account;
import java.util.List;
public class AccountImpl implements AccountDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public Account slelctAccountById(Integer id) {
List<Account> query = jdbcTemplate.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), id);
return query.isEmpty()?null:query.get(0);
}
public Account selectAccountByName(String name) {
List<Account> query = jdbcTemplate.query("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), name);
if (query.isEmpty())return null;
else if (query.size()>1)throw new RuntimeException("结果集不唯一");
else return query.get(0);
}
public void updateAccount(Account account) {
jdbcTemplate.update("update account set name = ?,money = ? where id = ?",account.getName(),account.getMoney(),account.getId());
}
}
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///spring"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--配置账户持久层-->
<bean id="accountDao" class="wf.dao.impl.AccountImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
</beans>
1.3.2、第二种方式:让 dao 继承 JdbcDaoSupport
JdbcDaoSupport 是spring 框架为我们提供的一个类,该类中定义了一个 JdbcTemplate 对象,我们可以直接获取使用,但是要想创建该对象,需要为其提供一个数据源:具体源码如下:
public abstract class JdbcDaoSupport extends DaoSupport {
//定义对象
private JdbcTemplate jdbcTemplate;
//set 方法注入数据源,判断是否注入了,注入了就创建 JdbcTemplate
public final void setDataSource(DataSource dataSource) {
if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()){ //如果提供了数据源就创建 JdbcTemplate
this.jdbcTemplate = createJdbcTemplate(dataSource);
initTemplateConfig();
}
}
//使用数据源创建 JdcbTemplate
protected JdbcTemplate createJdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
//当然,我们也可以通过注入 JdbcTemplate 对象
public final void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
initTemplateConfig();
}
//使用 getJdbcTmeplate 方法获取操作模板对象
public final JdbcTemplate getJdbcTemplate() {
return this.jdbcTemplate;
}
===================================================================================
/**
* 账户的接口
*/
public interface IAccountDao {
/**
* 根据 id 查询账户信息
* @param id
* @return
*/
Account findAccountById(Integer id);
/**
* 根据名称查询账户信息
* @return
*/
Account findAccountByName(String name);
/**
* 更新账户信息
* @param account
*/
void updateAccount(Account account);
}
===============================================================================
/**
* 账户的持久层实现类
* 此版本 dao,只需要给它的父类注入一个数据源
*/
public class AccountDaoImpl2 extends JdbcDaoSupport implements IAccountDao {
@Override
public Account findAccountById(Integer id) {
//getJdbcTemplate()方法是从父类上继承下来的。
List<Account> list = getJdbcTemplate().query("select * from account where
id = ? ",new AccountRowMapper(),id);
return list.isEmpty()?null:list.get(0);
}
@Override
public Account findAccountByName(String name) {
//getJdbcTemplate()方法是从父类上继承下来的。
List<Account> list = getJdbcTemplate().query("select * from account where
name = ? ",new AccountRowMapper(),name);
if(list.isEmpty()){
return null;
}
if(list.size()>1){
throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
}
return list.get(0);
}
@Override
public void updateAccount(Account account) {
//getJdbcTemplate()方法是从父类上继承下来的。
getJdbcTemplate().update("update account set money = ? where id = ?
",account.getMoney(),account.getId());
}
}
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置 dao2 -->
<bean id="accountDao2" class="com.itheima.dao.impl.AccountDaoImpl2">
<!-- 注入 dataSource -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///spring_day04"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>
</beans>
第一种在 Dao 类中定义 JdbcTemplate 的方式,适用于所有配置方式(xml 和注解都可以)。
让 第二种让 Dao 继承 JdbcDaoSupport 的方式,只能用于基于 XML 的方式,注解用不了。
SSM框架之Spring(5)JdbcTemplate及spring事务控制的更多相关文章
- Spring的 JDBCTemplate和声明式事务控制
Spring 中的 JdbcTemplate[会用] JdbcTemplate 概述 它是 spring 框架中提供的一个对象,是对原始 Jdbc API 对象的简单封装.spring 框架为我们提供 ...
- SSM框架Web程序的流程(Spring SpringMVC Mybatis)
SSM框架的Web程序主要用到了三个技术: Spring:用到了注解和自动装配,就是Spring的两个精髓IOC(反向控制)和 AOP(面向切面编程). SpringMVC:用到了MVC模型,将逻辑代 ...
- spring与mybatis集成和事务控制
一个. 基本介绍 本文将使用spring整合mybatis, 并加入事务管理, 以此为记, 方便以后查阅. 二. 样例 1. 代码结构图: 2. 建表语句: DROP DATABASE test; C ...
- SSM框架整合(IntelliJ IDEA + maven + Spring + SpringMVC + MyBatis)
本篇文章主要内容是介绍如何使用IntelliJ IDEA创建Spring + SpringMVC + MyBatis项目,下面会给出项目搭建的详细步骤以及相关的配置文件. 1. 创建maven项目 ...
- SSM框架的搭建和测试(Spring+Spring MVC+MyBatis)
Spring MVC:MVC框架,通过Model-View-Controller模式很好的将数据,业务与展现进行分离. MyBatis:数据持久层框架 我这里使用的是MyEclipse 2016 CI ...
- spring 学习(四): spring 的 jdbcTemplate 操作
spring 学习(四): spring 的 jdbcTemplate 操作 spring 针对 javaee 的每一层,都提供了相应的解决技术,jdbcTemplate 的主要操作在 dao 层. ...
- Java EE互联网轻量级框架整合开发— SSM框架(中文版带书签)、原书代码
Java EE互联网轻量级框架整合开发 第1部分 入门和技术基础 第1章 认识SSM框架和Redis 2 1.1 Spring框架 2 1.2 MyBatis简介 6 1.3 Spring MVC简介 ...
- SSM框架——以注解形式实现事务管理
上一篇博文<SSM三大框架整合详细教程>详细说了如何整合Spring.SpringMVC和MyBatis这三大框架.但是没有说到如何配置mybatis的事务管理,在编写业务的过程中,会需要 ...
- Spring第八篇【XML、注解实现事务控制】
前言 本博文主要讲解Spring的事务控制,如何使用Spring来对程序进行事务控制-. 一般地,我们事务控制都是在service层做的..为什么是在service层而不是在dao层呢??有没有这样的 ...
- ssm框架搭建和整合流程
Spring + SpringMVC + Mybatis整合流程 1 需求 1.1 客户列表查询 1.2 根据客户姓名模糊查询 2 整合思路 第一步:整合dao层 ...
随机推荐
- C#线程学习笔记十:async & await入门三
一.Task.Yield Task.Yield简单来说就是创建时就已经完成的Task,或者说执行时间为0的Task,或者说是空任务,也就是在创建时就将Task的IsCompeted值设置为0. 我们知 ...
- Teigha.net实体属性注释
Polyline3d: 3D polyline的类型由PolyType属性存储, 它是由Poly3dType枚举定义的整数值.PolyType属性是一种绘制三维折线的近似方法 Polyline3d p ...
- ffmpeg+nginx 实现rtsp转rtmp并通过nginx转发
Windows安装 ffmpeg ffmpeg windows版下载地址https://ffmpeg.zeranoe.com/builds/ static版本就行 配置环境变量:下载的压缩包解压后的路 ...
- LICEcap 动画屏幕录制软件
下载地址 https://licecap.en.softonic.com/ LICEcap捕捉屏幕的区域并保存为gif动画或lcf格式 效果请看下面的链接 https://www.cnblogs ...
- 一起学Spring之三种注入方式及集合类型注入
本文主要讲解Spring开发中三种不同的注入方式,以及集合数据类型的注入,仅供学习分享使用,如有不足之处,还请指正. 概述 Spring的注入方式一共有三种,如下所示: 通过set属性进行注入,即通过 ...
- C#实现地图坐标系的转换(WGS-84、GCJ-02、BD-09)
WGS-84坐标系:全球定位系统使用,GPS.北斗等 GCJ-02坐标系:中国地区使用,由WGS-84偏移而来 BD-09坐标系:百度专用,由GCJ-02偏移而来 (PS:源于项目需求,本来是想读图 ...
- 更换国内pip
pip国内的一些镜像 原始地址:https://pypi.python.org/simple 国内地址: 阿里云 http://mirrors.aliyun.com/pypi/simple/ 中国科技 ...
- Python第一个程序Hello Word
[源代码] print('Hello Python World!') [过程] 打开命令提示窗口(cmd),在源程序所在路径下执行,python 文件名.py. [截图]
- 利用Azure虚拟机安装Dynamics 365 Customer Engagement之十三:从可用性组中移除副本然后重新添加
我是微软Dynamics 365 & Power Platform方面的工程师罗勇,也是2015年7月到2018年6月连续三年Dynamics CRM/Business Solutions方面 ...
- 解决测试redis集群时报"java.lang.NumberFormatException: For input string: "7003@17003..7002@17002"等异常
一.前言 关于redis5.0的集群模式下,通过客户端测试代码调试报"Exception in thread "main" java.lang.NumberFormatE ...