notebook notebook
首页
  • 计算机网络
  • 计算机系统
  • 数据结构与算法
  • 计算机专业课
  • 设计模式
  • 前端 (opens new window)
  • Java 开发
  • Python 开发
  • Golang 开发
  • Git
  • 软件设计与架构
  • 大数据与分布式系统
  • 常见开发工具

    • Nginx
  • 爬虫
  • Python 数据分析
  • 数据仓库
  • 中间件

    • MySQL
    • Redis
    • Elasticsearch
    • Kafka
  • 深度学习
  • 机器学习
  • 知识图谱
  • 图神经网络
  • 应用安全
  • 渗透测试
  • Linux
  • 云原生
面试
  • 收藏
  • paper 好句
GitHub (opens new window)

学习笔记

啦啦啦,向太阳~
首页
  • 计算机网络
  • 计算机系统
  • 数据结构与算法
  • 计算机专业课
  • 设计模式
  • 前端 (opens new window)
  • Java 开发
  • Python 开发
  • Golang 开发
  • Git
  • 软件设计与架构
  • 大数据与分布式系统
  • 常见开发工具

    • Nginx
  • 爬虫
  • Python 数据分析
  • 数据仓库
  • 中间件

    • MySQL
    • Redis
    • Elasticsearch
    • Kafka
  • 深度学习
  • 机器学习
  • 知识图谱
  • 图神经网络
  • 应用安全
  • 渗透测试
  • Linux
  • 云原生
面试
  • 收藏
  • paper 好句
GitHub (opens new window)
  • Java开发

    • My

    • Posts

    • Java SE

    • Java 并发编程

    • JVM

    • JDBC

    • Java Web

    • Spring 与 SpringMVC

      • Spring 的 IOC 和 DI
      • Spring MVC 入门
      • Spring 拦截器、异常处理与 AOP
      • Spring 事务控制
        • 1. 事务控制
          • 1.1 编程式事务控制相关对象(了解即可)
          • 1.2 基于 XML 的声明式事务控制
          • 1.3 使用注解配置声明式事务控制
    • Spring Boot

    • Spring Cloud

    • Spring Security

    • Netty

    • MyBatis

  • Python开发

  • Golang开发

  • Git

  • 软件设计与架构

  • 大数据与分布式系统

  • 区块链

  • Nginx

  • 开发
  • Java开发
  • Spring 与 SpringMVC
yubin
2022-02-13
目录

Spring 事务控制

# 1. 事务控制

# 1.1 编程式事务控制相关对象(了解即可)

# 1.1.1 PlatformTransactionManager

PlatformTransactionManager 接口是 spring 的事务管理器,它里面提供了我们常用的操作事务的方法。

方法 说明
TransactionStatus getTransaction(TransactionDefination defination) 获取事务的状态信息
void commit(TransactionStatus status) 提交事务
void rollback(TransactionStatus status) 回滚事务

PlatformTransactionManager 是接口类型,不同的 Dao 层技术则有不同的实现类,例如:Dao 层技术是 jdbc 或 MyBatis 时:org.springframework.jdbc.datasource.DataSourceTransactionManager Dao 层技术是hibernate时:org.springframework.orm.hibernate5.HibernateTransactionManager

# 1.1.2 TransactionDefinition

TransactionDefinition 是事务的定义信息对象,里面有如下方法:

方法 说明
int getIsolationLevel() 获得事务的隔离级别
int getPropogationBehavior() 获得事务的传播行为
int getTimeout() 获得超时时间
boolean isReadOnly() 是否只读
# 1.1.2.1 事务隔离级别

设置事务隔离级别,可以解决事务并发产生的问题,如脏读、不可重复读和虚读。

  • ISOLATION_DEFAULT
  • ISOLATION_READ_UNCOMMITTED 【读未提交】
  • ISOLATION_READ_COMMITTED 【读已提交】
  • ISOLATION_REPEATABLE_READ 【可重复读】
  • ISOLATION_SERIALIZABLE 【可序列化】
# 1.1.2.2 事务传播行为

事务传播行为(propagation behavior)指的就是当一个事务方法被另一个事务方法调用时,这个事务方法应该如何进行。 例如:methodA 事务方法调用 methodB 事务方法时,methodB 是继续在调用者 methodA 的事务中运行呢,还是为自己开启一个新事务运行,这就是由 methodB 的事务传播行为决定的。

  • REQUIRED:如果当前没有事务,就新建一个事务;如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)

  • SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)

  • ... 其他的行为搜索即可

PS:都不用记,现用现查即可。

超时时间:默认值是 -1,没有超时限制。如果有,以秒为单位进行设置。

是否只读:建议查询时设置为只读。

# 1.1.3 TransactionStatus

TransactionStatus 接口提供的是事务具体的运行状态,方法介绍如下:

方法 说明
boolean hasSavepoint() 是否存储回滚点
boolean isCompleted() 事务是否完成
boolean isNewTransaction() 是否是新事务
boolean isRollbackOnly() 事务是否回滚

# 1.2 基于 XML 的声明式事务控制

# 1.2.1 什么是声明式事务控制

Spring 的声明式事务顾名思义就是采用声明的方式来处理事务。这里所说的声明,就是指在配置文件中声明 ,用在 Spring 配置文件中声明式的处理事务来代替代码式的处理事务。

  • 事务管理不侵入开发的组件。具体来说,业务逻辑对象就不会意识到正在事务管理之中,事实上也应该如此,因为事务管理是属于系统层面的服务,而不是业务逻辑的一部分,如果想要改变事务管理策划的话,也只需要在定义文件中重新配置即可。
  • 在不需要事务管理的时候,只要在设定文件上修改一下,即可移去事务管理服务,无需改变代码重新编译 ,这样维护起来极其方便

Spring 声明式事务控制底层就是 AOP。

为什么使用 AOP?

假设有如下转账代码:







 



 



public class AccountServiceImpl implements AccountService {

    private AccountDao accountDao;
    ...
        
    public void transfer(String outMan, String inMan, double money) {
        // 要开启事务
        accountDao.out(outMan, money);
        int i = 1 / 0;
        accountDao.in(inMan, money);
        // 提交事务
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

如果用于转账的方法 transfer 需要进行事务控制,则需要在 7、8 行处的注释处添加用于事务控制的代码,而如果很多方法都要这么做,那很容易联想到用 AOP 来实现从而解耦合。

# 1.2.2 声明式事务控制的实现

声明式事务控制明确事项:

  • 谁是切点?—— 转账的方法 transfer
  • 谁是通知?—— 事务控制的功能
  • 配置切面?—— AOP 的配置
# 1)引入 pom 坐标

增加 spring-tx 的包

# 2)引入 tx 命名空间




 





 
 



<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/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
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 3)配置事务增强
<!--平台事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource"></property>
</bean>

<!--事务增强配置-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
  <tx:attributes>
    <tx:method name="*"/>
  </tx:attributes>
</tx:advice>
1
2
3
4
5
6
7
8
9
10
11
# 4)配置事务 AOP 织入
<!--事务的aop增强-->
<aop:config>
  <aop:pointcut id="myPointcut" expression="execution(*com.example.service.impl.*.*(..))"/>
  <aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut"></aop:advisor>
</aop:config>
1
2
3
4
5
# 5)测试事务控制转账业务代码
@Override
public void transfer(String outMan, String inMan, double money) {
	accountDao.out(outMan,money);
	int i = 1/0;
	accountDao.in(inMan,money);
}
1
2
3
4
5
6

# 1.2.3 切点方法的事务参数的配置

<!--事务增强配置-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
  <tx:attributes>
    <tx:method name="*"/>
  </tx:attributes>
</tx:advice>
1
2
3
4
5
6

其中,<tx:method> 代表切点方法的事务参数的配置,例如:

<tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="-1" read-only="false"/>:

  • name:切点方法名称
  • isolation:事务的隔离级别
  • propogation:事务的传播行为
  • timeout:超时时间
  • read-only:是否只读

# 1.3 使用注解配置声明式事务控制

# 1.3.1 快速入门

# 1)编写 AccoutDao
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
	@Autowired
	private JdbcTemplate jdbcTemplate;
    
	public void out(String outMan, double money) {
		jdbcTemplate.update("update account set money=money-? where name=?",money,outMan);
	}
    
	public void in(String inMan, double money) {
		jdbcTemplate.update("update account set money=money+? where name=?",money,inMan);
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
# 2)编写 AccoutService
@Service("accountService")
@Transactional
public class AccountServiceImpl implements AccountService {
	@Autowired
	private AccountDao accountDao;
    
	@Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
	public void transfer(String outMan, String inMan, double money) {
		accountDao.out(outMan,money);
		int i = 1/0;
		accountDao.in(inMan,money);
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
# 3)编写 applicationContext.xml 配置文件
<!--之前省略datsSource、jdbcTemplate、平台事务管理器的配置-->
<!--组件扫描-->
<context:component-scan base-package="com.example"/>
<!--事务的注解驱动-->
<tx:annotation-driven/>
1
2
3
4
5

# 1.3.2 注解配置声明式事务控制解析

  • 使用 @Transactional 在需要进行事务控制的类或是方法上修饰,注解可用的属性同 xml 配置方式,例如隔离级别、传播行为等。
  • 注解使用在类上,那么该类下的所有方法都使用同一套注解参数配置。
  • 使用在方法上,不同的方法可以采用不同的事务参数配置。
  • XML 配置文件中要开启事务的注解驱动 <tx:annotation-driven />
编辑 (opens new window)
上次更新: 2023/04/22, 08:56:42
Spring 拦截器、异常处理与 AOP
Spring Boot 2 基础入门

← Spring 拦截器、异常处理与 AOP Spring Boot 2 基础入门→

最近更新
01
Deep Reinforcement Learning
10-03
02
误删数据后怎么办
04-06
03
MySQL 一主多从
03-22
更多文章>
Theme by Vdoing | Copyright © 2021-2024 yubincloud | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
×