【Spring】Spring 事务控制
Spring 事务控制
Spring 事务控制介绍
JavaEE 体系进行分层开发,事务控制位于业务层,Spring 提供了分层设计业务层的事务处理解决方案。
Spring 的事务控制都是基于 AOP 的,它既可以使用编程的方式实现,也可以使用配置的方式实现。但是推荐以配置的方式实现。
PlatformTransactionManager 接口是提供事务操作的方法,它包含的获取事务状态信息、提交事务、回滚事务等方法。
DataSourceTransactionManager 实现类用于 Spring JdbcTemplate 或 MyBatis 持久化数据。
事务的传播行为:
- REQUIRED 如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般用于增删改操作
- SUPPORTS 支持当前事务,如果当前没有事务,就以非事务方式执行。一般用于查操作
- MANDATORY 使用当前的事务,如果当前没有事务,就抛出异常
- REQUERS_NEW 新建事务,如果当前在事务中,把当前事务挂起
- NOT_SUPPORTED 以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
- NEVER 以非事务方式运行,如果当前存在事务,抛出异常
- NESTED 如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行 REQUIRED 类似的操作
XML 的 事务控制
使用步骤:
- 创建 Spring 的配置文件并导入约束
- 准备数据库表和实体类
- 编写持久层接口和实现类
- 编写业务层接口和实现类
- 编写配置文件
- 在配置文件中配置持久层和业务
- 配置数据源
- 配置事务相关:
- 配置事务管理器
- 配置事务的通知
- 配置事务的属性
- 配置 AOP
- 配置 AOP 切入点表达式
- 配置切入点表达式和事务通知的对应关系
账户的持久层接口的实现类:AccountDAOImpl.java
package cn.parzulpan.dao;
import cn.parzulpan.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import java.util.List;
/**
* @Author : parzulpan
* @Time : 2020-12
* @Desc : 账户的持久层接口的实现类
*/
public class AccountDAOImpl extends JdbcDaoSupport implements AccountDAO {
public Account findById(Integer accountId) {
List<Account> accounts = getJdbcTemplate().query("select * from bankAccount where id = ?",
new BeanPropertyRowMapper<Account>(Account.class),
accountId);
return accounts.isEmpty() ? null : accounts.get(0);
}
public Account findByName(String name) {
List<Account> accounts = getJdbcTemplate().query("select * from bankAccount where name = ?",
new BeanPropertyRowMapper<Account>(Account.class),
name);
if (accounts.isEmpty()) {
return null;
}
if (accounts.size() > 1) {
throw new RuntimeException("结果集不唯一");
}
return accounts.get(0);
}
public void update(Account account) {
getJdbcTemplate().update("update bankAccount set name = ?, money = ? where id = ?",
account.getName(), account.getMoney(), account.getId());
}
}
账户的持久层接口的实现类:AccountServiceImpl.java
package cn.parzulpan.service;
import cn.parzulpan.dao.AccountDAO;
import cn.parzulpan.domain.Account;
/**
* @Author : parzulpan
* @Time : 2020-12
* @Desc : 账户的业务层接口的实现类,事务控制应该在业务层
*/
public class AccountServiceImpl implements AccountService {
private AccountDAO accountDAO;
public void setAccountDAO(AccountDAO accountDAO) {
this.accountDAO = accountDAO;
}
public Account findById(Integer accountId) {
return accountDAO.findById(accountId);
}
public void transfer(String sourceName, String targetName, Double money) {
System.out.println("开始进行转账...");
Account source = accountDAO.findByName(sourceName);
Account target = accountDAO.findByName(targetName);
source.setMoney(source.getMoney() - money);
target.setMoney(target.getMoney() + money);
accountDAO.update(source);
int i = 1 / 0; // 模拟转账故障
accountDAO.update(target);
System.out.println("转账完成...");
}
}
配置文件:bean.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 配置账户业务层 -->
<bean id="accountService" class="cn.parzulpan.service.AccountServiceImpl">
<property name="accountDAO" ref="accountDAO"/>
</bean>
<!-- 配置账户持久层 -->
<bean id="accountDAO" class="cn.parzulpan.dao.AccountDAOImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/springT?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- 1. 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 2. 配置事务的通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 3. 配置事务的属性
指定是业务核心方法
read-only:是否是只读事务。默认 false,不只读。
isolation:指定事务的隔离级别。默认值是使用数据库的默认隔离级别。
propagation:指定事务的传播行为。
timeout:指定超时时间。默认值为:-1。永不超时。
rollback-for:用于指定一个异常,当执行产生该异常时,事务回滚。产生其他异常,事务不回滚。
没有默认值,任何异常都回滚。
no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回滚。
没有默认值,任何异常都回滚。
-->
<tx:attributes>
<tx:method name="*" read-only="false" propagation="REQUIRED"/>
<!-- 查询方法 -->
<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
</tx:attributes>
</tx:advice>
<!-- 4. 配置 AOP -->
<aop:config>
<!-- 5. 配置 AOP 切入点表达式 -->
<aop:pointcut id="allServiceImplPCR" expression="execution(* cn.parzulpan.service.*.*(..))"/>
<!-- 6. 配置切入点表达式和事务通知的对应关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="allServiceImplPCR"/>
</aop:config>
</beans>
对 账户的业务层 进行单元测试:AccountServiceImplTest.java
package cn.parzulpan.service;
import cn.parzulpan.domain.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.*;
/**
* @Author : parzulpan
* @Time : 2020-12
* @Desc : 对 账户的业务层 进行单元测试
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceImplTest {
@Autowired
private AccountService as;
@Test
public void findById() {
Account account = as.findById(1);
System.out.println(account);
}
@Test
public void transfer() {
as.transfer("aaa", "bbb", 100.0);
}
}
注解 的 事务控制
使用步骤:
- 其他同 XML 的 事务控制
- 编写配置文件
- 配置事务管理器
- 开启对注解事务的支持
- 在需要事务支持的地方使用 @Transactional
账户的持久层接口的实现类:AccountDAOImpl.java
package cn.parzulpan.dao;
import cn.parzulpan.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author : parzulpan
* @Time : 2020-12
* @Desc : 账户的持久层接口的实现类
*/
@Repository("accountDAO")
public class AccountDAOImpl implements AccountDAO {
@Resource(name = "jdbcTemplate")
private JdbcTemplate jdbcTemplate;
public Account findById(Integer accountId) {
List<Account> accounts = jdbcTemplate.query("select * from bankAccount where id = ?",
new BeanPropertyRowMapper<Account>(Account.class),
accountId);
return accounts.isEmpty() ? null : accounts.get(0);
}
public Account findByName(String name) {
List<Account> accounts = jdbcTemplate.query("select * from bankAccount where name = ?",
new BeanPropertyRowMapper<Account>(Account.class),
name);
if (accounts.isEmpty()) {
return null;
}
if (accounts.size() > 1) {
throw new RuntimeException("结果集不唯一");
}
return accounts.get(0);
}
public void update(Account account) {
jdbcTemplate.update("update bankAccount set name = ?, money = ? where id = ?",
account.getName(), account.getMoney(), account.getId());
}
}
账户的持久层接口的实现类:AccountServiceImpl.java
package cn.parzulpan.service;
import cn.parzulpan.dao.AccountDAO;
import cn.parzulpan.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
/**
* @Author : parzulpan
* @Time : 2020-12
* @Desc : 账户的业务层接口的实现类,事务控制应该在业务层
*/
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Resource(name = "accountDAO")
private AccountDAO accountDAO;
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public Account findById(Integer accountId) {
return accountDAO.findById(accountId);
}
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public void transfer(String sourceName, String targetName, Double money) {
System.out.println("开始进行转账...");
Account source = accountDAO.findByName(sourceName);
Account target = accountDAO.findByName(targetName);
source.setMoney(source.getMoney() - money);
target.setMoney(target.getMoney() + money);
accountDAO.update(source);
int i = 1 / 0; // 模拟转账故障
accountDAO.update(target);
System.out.println("转账完成...");
}
}
配置文件:bean.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="cn.parzulpan"/>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/springT?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- 1. 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 2. 开启对注解事务的支持 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 3. 在需要事务支持的地方使用 @Transactional -->
</beans>
总结和练习
【Spring】Spring 事务控制的更多相关文章
- 13 Spring 的事务控制
1.事务的概念 理解事务之前,先讲一个你日常生活中最常干的事:取钱. 比如你去ATM机取1000块钱,大体有两个步骤:首先输入密码金额,银行卡扣掉1000元钱:然后ATM出1000元钱.这两个步骤必 ...
- 04 Spring:01.Spring框架简介&&02.程序间耦合&&03.Spring的 IOC 和 DI&&08.面向切面编程 AOP&&10.Spring中事务控制
spring共四天 第一天:spring框架的概述以及spring中基于XML的IOC配置 第二天:spring中基于注解的IOC和ioc的案例 第三天:spring中的aop和基于XML以及注解的A ...
- spring的事务控制
1.事务介绍 (1)特性:ACID Atomicity(原子性):事务中的所有操作要么全做要么全不做 Consistency(一致性):事务执行的结果使得数据库从一个一致性状态转移到另一个一致性状态 ...
- 阶段3 2.Spring_10.Spring中事务控制_9 spring编程式事务控制1-了解
编程式的事物控制,使用的情况非常少,主要作为了解 新建项目 首先导入包坐标 复制代码 这里默认值配置了Service.dao和连接池其他的内容都没有配置 也就说现在是没有事物支持的.运行测试文件 有错 ...
- 阶段3 2.Spring_10.Spring中事务控制_8 spring基于纯注解的声明式事务控制
新建项目 把之前项目src下的内容全部复制过来 pom.xml内复制过来 开始配置 新建一个config的包,然后再新建配置文件类SpringConfiguration @Configuration这 ...
- 阶段3 2.Spring_10.Spring中事务控制_6 spring基于XML的声明式事务控制-配置步骤
环境搭建 新建工程 把对应的依赖复制过来 src下内容复制 配置spring中的声明事物 找到bean.xml开始配置 配置事物管理器 里面需要注入DataSource 2-配置事物通知 需要先导入事 ...
- 阶段3 2.Spring_10.Spring中事务控制_5 spring事务控制的代码准备
创建一个工程,只搭建环境不做配置.等配置的时候把这个项目相关的代码再复制到新项目里面 jar包的打包方式 导入包 事务控制也是基于AOP的.所以这里导入aspectjweaver 复制jdbcTemp ...
- 阶段3 2.Spring_10.Spring中事务控制_4 spring中事务控制的一组API
分析aop的 xml 的代码.更直观一些 事务提交和回滚就是我们重复的代码 spring业余事务管理器,我们拿过来直接用就可以 提交和回滚的后面直接调用释放.所以释放资源之类就是多余的 在绑定连接到线 ...
- 阶段3 2.Spring_10.Spring中事务控制_1 基于XML的AOP实现事务控制
新建项目 首先把依赖复制进来 aop必须引入.aspectjweaver 复制src下的所有内容 复制到我们的新项目里面 factory文件夹删掉 删除后测试类必然就报错 配置文件 beanFacto ...
- Spring的事务控制-基于注解的方式
模拟转账操作,即Jone减少500,tom增加500 如果有疑问请访问spring事务控制-基于xml方式 1.创建数据表 2.创建Account实体类 public class Account { ...
随机推荐
- kafka命令及启动
默认内网访问,要在外网访问的话,需要在修改config/server.properties中的配置 将listeners和advertised.listeners的值用主机名进行替换,在外用使用jav ...
- Chrome中Console使用技巧
1.使用Jquery 先在控制台执行一下 ;(function(d,s){d.body.appendChild(s=d.createElement('script')).src='https://cd ...
- js-enter提交表单导致页面刷新问题
问题:当页面只有一个文本框时,使用键盘enter操作执行提交表单的时候,会导致页面进行刷新,并且参数也会自动添加到url中. 解决办法: 1.给form添加onsubmit=return false; ...
- C# 学习第七天
P96 面向对象的概念 ①先有的 面向过程 --------> 然后才衍生出面向对象的思想 ②面向过程:面向的是完成这件事儿的过程,强调的是完成这件事儿的动作 比如说 把大象塞进冰箱去 ③面向过 ...
- 流程控制之☞ while 和 for 的故事
学习三连鞭... 什么是循环? 为什么要有循环? 如何用循环? 循环的基本语法:while 和 for 先来看while循环: while条件:首先得是个循环体. 1.如果条件为真,那么循 ...
- Python字符串常用的一些东西
字符串的常用方法dir(str).查看某一方法的用法help(str.xxx). 1,索引和切片: 2,len():查看字符串的总长度. 3,+,拼接一个或多个字符串. 4,in,判定字符是否在字符串 ...
- NET 5 Execl导入数据处理(EppLus、NPOI)
先来简单介绍下市面上最广泛常见的三种操作excel库的优缺点1.NPOI 优点:免费开源,无需装Office即可操作excel, 支持处理的文件格式包括xls, xlsx, docx.格式 缺点:不支 ...
- 【进程/作业管理】篇章四:Linux任务计划、周期性任务执行
命令归纳: at 未来时间点让特定任务运行一次 batch 未来时间点让系统自行选择在系统资源较空闲的时间去执行指定的任务 corn 周期性任务计划(corntad) at命令详解 <--- 假 ...
- android studio 找不到真机设备
连接USB之后没有显示连接,如下图 设备管理器: 解决:重启电脑
- iOS崩溃治理--开篇
去年我开始负责iOS崩溃治理的工作,从原来的万分之五崩溃率,一直到现在的万分之一左右的崩溃率,期间踩了很多坑,因此想和大家分享一下,希望能对大家有所帮助,也欢迎大家私信交流. 如果你打算开始治理崩溃的 ...