引言: 在Spring中@Transactional提供一种控制事务管理的快捷手段,但是很多人都只是@Transactional简单使用,并未深入了解,其各个配置项的使用方法,本文将深入讲解各个配置项的使用。

@Transactional的定义

Spring中的@Transactional基于动态代理的机制,提供了一种透明的事务管理机制,方便快捷解决在开发中碰到的问题。在现实中,实际的问题往往比我们预期的要复杂很多,这就要求对@Transactional有深入的了解,以来应对复杂问题。

首先我们来看看@Transactional的源代码定义:

org.springframework.transaction.annotation.Transactional


@Target({ElementType.METHOD, ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Inherited@Documentedpublic @interface Transactional {/*** A qualifier value for the specified transaction.* <p>May be used to determine the target transaction manager,* matching the qualifier value (or the bean name) of a specific* {@link org.springframework.transaction.PlatformTransactionManager}* bean definition.*/String value() default "";/*** The transaction propagation type.* Defaults to {@link Propagation#REQUIRED}.* @see org.springframework.transaction.interceptor.TransactionAttribute#getPropagationBehavior()*/Propagation propagation() default Propagation.REQUIRED;/*** The transaction isolation level.* Defaults to {@link Isolation#DEFAULT}.* @see org.springframework.transaction.interceptor.TransactionAttribute#getIsolationLevel()*/Isolation isolation() default Isolation.DEFAULT;/*** The timeout for this transaction.* Defaults to the default timeout of the underlying transaction system.* @see org.springframework.transaction.interceptor.TransactionAttribute#getTimeout()*/int timeout() default TransactionDefinition.TIMEOUT_DEFAULT;/*** {@code true} if the transaction is read-only.* Defaults to {@code false}.* <p>This just serves as a hint for the actual transaction subsystem;* it will <i>not necessarily</i> cause failure of write access attempts.* A transaction manager which cannot interpret the read-only hint will* <i>not</i> throw an exception when asked for a read-only transaction.* @see org.springframework.transaction.interceptor.TransactionAttribute#isReadOnly()*/boolean readOnly() default false;/*** Defines zero (0) or more exception {@link Class classes}, which must be a* subclass of {@link Throwable}, indicating which exception types must cause* a transaction rollback.* <p>This is the preferred way to construct a rollback rule, matching the* exception class and subclasses.* <p>Similar to {@link org.springframework.transaction.interceptor.RollbackRuleAttribute#RollbackRuleAttribute(Class clazz)}*/Class<? extends Throwable>[] rollbackFor() default {};/*** Defines zero (0) or more exception names (for exceptions which must be a* subclass of {@link Throwable}), indicating which exception types must cause* a transaction rollback.* <p>This can be a substring, with no wildcard support at present.* A value of "ServletException" would match* {@link javax.servlet.ServletException} and subclasses, for example.* <p><b>NB: </b>Consider carefully how specific the pattern is, and whether* to include package information (which isn't mandatory). For example,* "Exception" will match nearly anything, and will probably hide other rules.* "java.lang.Exception" would be correct if "Exception" was meant to define* a rule for all checked exceptions. With more unusual {@link Exception}* names such as "BaseBusinessException" there is no need to use a FQN.* <p>Similar to {@link org.springframework.transaction.interceptor.RollbackRuleAttribute#RollbackRuleAttribute(String exceptionName)}*/String[] rollbackForClassName() default {};/*** Defines zero (0) or more exception {@link Class Classes}, which must be a* subclass of {@link Throwable}, indicating which exception types must <b>not</b>* cause a transaction rollback.* <p>This is the preferred way to construct a rollback rule, matching the* exception class and subclasses.* <p>Similar to {@link org.springframework.transaction.interceptor.NoRollbackRuleAttribute#NoRollbackRuleAttribute(Class clazz)}*/Class<? extends Throwable>[] noRollbackFor() default {};/*** Defines zero (0) or more exception names (for exceptions which must be a* subclass of {@link Throwable}) indicating which exception types must <b>not</b>* cause a transaction rollback.* <p>See the description of {@link #rollbackForClassName()} for more info on how* the specified names are treated.* <p>Similar to {@link org.springframework.transaction.interceptor.NoRollbackRuleAttribute#NoRollbackRuleAttribute(String exceptionName)}*/String[] noRollbackForClassName() default {};}

基于源代码,我们可以发现在@Transactional中,原来有这么多的属性可以进行配置,从而达到复杂应用控制的目的。具体各个属性的用法和作用,将在下面逐一进行讲解和说明。

@Transactional注解中常用参数说明

参数名称 | 功能描述

-------------|---------------

readOnly |该属性用于设置当前事务是否为只读事务,设置为true表示只读,false则表示可读写,默认值为false。例如:@Transactional(readOnly=true)

rollbackFor|该属性用于设置需要进行回滚的异常类数组,当方法中抛出指定异常数组中的异常时,则进行事务回滚。例如:指定单一异常类:@Transactional(rollbackFor=RuntimeException.class)指定多个异常类:@Transactional(rollbackFor={RuntimeException.class, Exception.class})

rollbackForClassName|该属性用于设置需要进行回滚的异常类名称数组,当方法中抛出指定异常名称数组中的异常时,则进行事务回滚。例如:指定单一异常类名称:@Transactional(rollbackForClassName="RuntimeException")指定多个异常类名称:@Transactional(rollbackForClassName={"RuntimeException","Exception"})

noRollbackFor|该属性用于设置不需要进行回滚的异常类数组,当方法中抛出指定异常数组中的异常时,不进行事务回滚。例如:指定单一异常类:@Transactional(noRollbackFor=RuntimeException.class)指定多个异常类:@Transactional(noRollbackFor={RuntimeException.class, Exception.class})

noRollbackForClassName|该属性用于设置不需要进行回滚的异常类名称数组,当方法中抛出指定异常名称数组中的异常时,不进行事务回滚。例如:指定单一异常类名称:@Transactional(noRollbackForClassName="RuntimeException")指定多个异常类名称:@Transactional(noRollbackForClassName={"RuntimeException","Exception"})

propagation|该属性用于设置事务的传播行为,具体取值可参考表6-7。例如:@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)

isolation|该属性用于设置底层数据库的事务隔离级别,事务隔离级别用于处理多事务并发的情况,通常使用数据库的默认隔离级别即可,基本不需要进行设置

timeout|该属性用于设置事务的超时秒数,默认值为-1表示永不超时

事物传播行为介绍:

    @Transactional(propagation=Propagation.REQUIRED) :如果有事务, 那么加入事务, 没有的话新建一个(默认情况下)@Transactional(propagation=Propagation.NOT_SUPPORTED) :容器不为这个方法开启事务@Transactional(propagation=Propagation.REQUIRES_NEW) :不管是否存在事务,都创建一个新的事务,原来的挂起,新的执行完毕,继续执行老的事务@Transactional(propagation=Propagation.MANDATORY) :必须在一个已有的事务中执行,否则抛出异常@Transactional(propagation=Propagation.NEVER) :必须在一个没有的事务中执行,否则抛出异常(与Propagation.MANDATORY相反)@Transactional(propagation=Propagation.SUPPORTS) :如果其他bean调用这个方法,在其他bean中声明事务,那就用事务.如果其他bean没有声明事务,那就不用事务.@Transactional(propagation=Propagation.NESTED) : 如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则进行与PROPAGATION_REQUIRED类似的操作。前六个策略类似于EJB CMT,第七个(PROPAGATION_NESTED)是Spring所提供的一个特殊变量。 它要求事务管理器或者使用JDBC 3.0 Savepoint API提供嵌套事务行为(如Spring的DataSourceTransactionManager)

事物超时设置:

@Transactional(timeout=30) //默认是30秒

事务隔离级别:

@Transactional(isolation = Isolation.READ_UNCOMMITTED):读取未提交数据(会出现脏读, 不可重复读) 基本不使用

@Transactional(isolation = Isolation.READ_COMMITTED):读取已提交数据(会出现不可重复读和幻读)

@Transactional(isolation = Isolation.REPEATABLE_READ):可重复读(会出现幻读)

@Transactional(isolation = Isolation.SERIALIZABLE):串行化

MYSQL: 默认为REPEATABLE_READ级别

SQLSERVER: 默认为READ_COMMITTED

脏读 : 一个事务读取到另一事务未提交的更新数据

不可重复读 : 在同一事务中, 多次读取同一数据返回的结果有所不同, 换句话说,

后续读取可以读到另一事务已提交的更新数据.

可重复读:在同一事务中多次

读取数据时, 能够保证所读数据一样, 也就是后续读取不能读到另一事务已提交的更新数据

幻读 : 一个事务读到另一个事务已提交的insert数据

注意的几点:

1、@Transactional 只能被应用到public方法上, 对于其它非public的方法,如果标记了@Transactional也不会报错,但方法没有事务功能.

2、用 spring 事务管理器,由spring来负责数据库的打开,提交,回滚.默认遇到运行期例外(throw new RuntimeException("注释");)会回滚,即遇到不受检查(unchecked)的例外时回滚;而遇到需要捕获的例外(throw new Exception("注释");)不会回滚,即遇到受检查的例外(就是非运行时抛出的异常,编译器会检查到的异常叫受检查例外或说受检查异常)时,需我们指定方式来让事务回滚要想所有异常都回滚,要加上 @Transactional( rollbackFor={Exception.class,其它异常}) .如果让unchecked例外不回滚: @Transactional(notRollbackFor=RunTimeException.class)

如下:


1 @Transactional(rollbackFor=Exception.class) //指定回滚,遇到异常Exception时回滚2 public void methodName() {3    throw new Exception("注释");4 }5 @Transactional(noRollbackFor=Exception.class)//指定不回滚,遇到运行期例外(throw new RuntimeException("注释");)会回滚6 public ItimDaoImpl getItemDaoImpl() {7    throw new RuntimeException("注释");8 }

3、@Transactional 注解应该只被应用到 public 可见度的方法上。 如果你在 protected、private 或者 package-visible 的方法上使用 @Transactional 注解,它也不会报错, 但是这个被注解的方法将不会展示已配置的事务设置。

4、@Transactional 注解可以被应用于接口定义和接口方法、类定义和类的 public 方法上。然而,请注意仅仅 @Transactional 注解的出现不足于开启事务行为,它仅仅 是一种元数据,能够被可以识别 @Transactional 注解和上述的配置适当的具有事务行为的beans所使用。上面的例子中,其实正是 元素的出现 开启 了事务行为。

5、Spring团队的建议是你在具体的类(或类的方法)上使用 @Transactional 注解,而不要使用在类所要实现的任何接口上。你当然可以在接口上使用 @Transactional 注解,但是这将只能当你设置了基于接口的代理时它才生效。因为注解是不能继承的,这就意味着如果你正在使用基于类的代理时,那么事务的设置将不能被基于类的代理所识别,而且对象也将不会被事务代理所包装(将被确认为严重的)。因此,请接受Spring团队的建议并且在具体的类上使用 @Transactional 注解。

补充

例子讲解以上七中事务传播机制

自己写的一个测试


@RunWith(SpringRunner.class)@SpringBootTest(classes = Application.class)public class UserBaseInfoControllerTest {@Autowiredprivate UserBaseInfoService userBaseInfoService;@Test@Transactional(propagation = Propagation.REQUIRED,rollbackFor = RuntimeException.class)public void testOne() {UserBaseInfo userBaseInfo = new UserBaseInfo();userBaseInfo.setId(3);userBaseInfo.setUserName("xu2");userBaseInfo.setPassWord("111111");userBaseInfoService.update(userBaseInfo);userBaseInfo.setUserName("xu1");userBaseInfo.setPassWord("1111111");userBaseInfoService.save(userBaseInfo);}}@Servicepublic class UserBaseInfoServiceImpl extends AbstractService<UserBaseInfo> implements UserBaseInfoService {@Resourceprivate UserBaseInfoMapper userBaseInfoMapper;@Overridepublic void save(UserBaseInfo userBaseInfo) {mapper.insertSelective(userBaseInfo);}@Override//@Transactional(propagation = Propagation.REQUIRED,rollbackFor = RuntimeException.class)//@Transactional(propagation=Propagation.REQUIRES_NEW,rollbackFor = RuntimeException.class)//@Transactional(propagation=Propagation.MANDATORY,rollbackFor = RuntimeException.class)//@Transactional(propagation=Propagation.NESTED,rollbackFor = RuntimeException.class)//@Transactional(propagation=Propagation.NEVER,rollbackFor = RuntimeException.class)//@Transactional(propagation=Propagation.NOT_SUPPORTED,rollbackFor = RuntimeException.class)//@Transactional(propagation=Propagation.SUPPORTS,rollbackFor = RuntimeException.class)public void update(UserBaseInfo userBaseInfo) {mapper.updateByPrimaryKeySelective(userBaseInfo);}

假设有类A的方法methodB(),有类B的方法methodB().

  1. PROPAGATION_REQUIRED

如果B的方法methodB()的事务传播特性是propagation_required,那么如下图

upload_ccf3aea9741cd3ccd53883b11f02eb0f.png

A.methodA()调用B的methodB()方法,那么如果A的方法包含事务,则B的方法则不从新开启事务,

1、 如果B的methodB()抛出异常,A的methodB()没有捕获,则A和B的事务都会回滚;

2、 如果B的methodB()运行期间异常会导致B的methodB()的回滚,A如果捕获了异常,并正常提交事务,则会发生Transaction rolled back because it has been marked as rollback-only的异常。

3、 如果A的methodA()运行期间异常,则A和B的Method的事务都会被回滚

  1. PROPAGATION_SUPPORTS

如果B的方法methodB()的事务传播特性是propagation_supports,么如下图

upload_ccf3aea9741cd3ccd53883b11f02eb0f.png

A.methodA()调用B的methodB()方法,那么如果A的方法包含事务,则B运行在此事务环境中,如果A的方法不包含事务,则B运行在非事务环境;

1、如果A没有事务,则A和B的运行出现异常都不会回滚。

2、如果A有事务,A的method方法执行抛出异常,B.methodB和A.methodA都会回滚。

3、如果A有事务,B.method抛出异常,B.methodB和A.methodA都会回滚,如果A捕获了B.method抛出的异常,则会出现异常Transactionrolled back because it has been marked as rollback-only。

  1. PROPAGATION_MANDATORY

表示当前方法必须在一个事务中运行,如果没有事务,将抛出异常,如下图调用关系:

upload_ccf3aea9741cd3ccd53883b11f02eb0f.png

B.methodB()事务传播特性定义为:PROPAGATION_MANDATORY

1、如果A的methoda()方法没有事务运行环境,则B的methodB()执行的时候会报如下异常:No existingtransaction found for transaction marked with propagation 'mandatory'

2、如果A的Methoda()方法有事务并且执行过程中抛出异常,则A.methoda()和B.methodb()执行的操作被回滚;

3、如果A的methoda()方法有事务,则B.methodB()抛出异常时,A的methoda()和B.methodB()都会被回滚;如果A捕获了B.method抛出的异常,则会出现异常Transaction rolled back because ithas been marked as rollback-only

  1. PROPAGATION_NESTED

如有一下方法调用关系,如图:

upload_ccf3aea9741cd3ccd53883b11f02eb0f.png

B的methodB()定义的事务为PROPAGATION_NESTED;

1、 如果A的MethodA()不存在事务,则B的methodB()运行在一个新的事务中,B.method()抛出的异常,B.methodB()回滚,但A.methodA()不回滚;如果A.methoda()抛出异常,则A.methodA()和B.methodB()操作不回。

2、 如果A的methodA()存在事务,则A的methoda()抛出异常,则A的methoda()和B的Methodb()都会被回滚;

3、 如果A的MethodA()存在事务,则B的methodB()抛出异常,B.methodB()回滚,如果A不捕获异常,则A.methodA()和B.methodB()都会回滚,如果A捕获异常,则B.methodB()回滚,A不回滚;

5)PROPAGATION_NEVER

表示事务传播特性定义为PROPAGATION_NEVER的方法不应该运行在一个事务环境中

有如下调用关系:

upload_ccf3aea9741cd3ccd53883b11f02eb0f.png

如果B.methodB()的事务传播特性被定义为PROPAGATION_NEVER,则如果A.methodA()方法存在事务,则会出现异常Existingtransaction found for transaction marked with propagation 'never'。

6)PROPAGATION_REQUIRES_NEW

表示事务传播特性定义为PROPAGATION_REQUIRES_NEW的方法需要运行在一个新的事务中。

如有以下调用关系:B.methodB()事务传播特性为PROPAGATION_REQUIRES_NEW.

upload_ccf3aea9741cd3ccd53883b11f02eb0f.png

1、 如果A存在事务,A.methodA()抛出异常,A.methodA()的事务被回滚,但B.methodB()事务不受影响;如果B.methodB()抛出异常,A不捕获的话,A.methodA()和B.methodB()的事务都会被回滚。如果A捕获的话,A.methodA()的事务不受影响但B.methodB()的事务回滚。

  1. PROPAGATION_NOT_SUPPORTED

表示该方法不应该在一个事务中运行。如果有一个事务正在运行,他将在运行期被挂起,直到这个事务提交或者回滚才恢复执行。

如有一下调用关系图:

upload_ccf3aea9741cd3ccd53883b11f02eb0f.png

如果B.methodB()方法传播特性被定义为:PROPAGATION_NOT_SUPPORTED。

1、 如果A.methodA()存在事务,如果B.methodB()抛出异常,A.methodA()不捕获的话,A.methodA()的事务被回滚,而B.methodB()出现异常前数据库操作不受影响。如果A.methodA()捕获的话,则A.methodA()的事务不受影响,B.methodB()异常抛出前的数据操作不受影响。

Spring @Transactional注解浅谈相关推荐

  1. spring@Transactional注解事务不回滚不起作用无效的问题处理

    这几天在项目里面发现我使用@Transactional注解事务之后,抛了异常居然不回滚.后来终于找到了原因. 如果你也出现了这种情况,可以从下面开始排查. 一.特性 先来了解一下@Transactio ...

  2. spring @Transactional注解参数详解

    事物注解方式: @Transactional 当标于类前时, 标示类中所有方法都进行事物处理 , 例子: @Transactional public class TestServiceBean imp ...

  3. spring@Transactional注解

    今天遇到一个Transaction rolled back because it has been marked as rollback-only错误,controller调用service的方法总是 ...

  4. java spring流程_浅谈SpringMVC执行过程

    通过深入分析Spring源码,我们知道Spring框架包括大致六大模块, 如Web模块,数据库访问技术模块,面向切面模块,基础设施模块,核心容器模块和模块, 其中,在Spring框架的Web模块中,又 ...

  5. Spring mcv 框架 浅谈

    spring mvc 提供了对web的支持.spring的这种支持使得spring可以像其他web层的框架一样搭建web层应用! spring mvc 核心技术主要围绕分发器(DispatcherSe ...

  6. 浅谈Spring注解

    Spring目前的趋势是使用注解结合Java代码而不是配置来定义行为.属性.功能.规则和扩展点,因此梳理注解也是梳理Spring功能点的很好的方式,全面的梳理可以补足我们知识点的漏洞. 查找所有注解 ...

  7. @transactional注解原理_《Spring源码解析(十二)》深入理解Spring事务原理,告别面试一问三不知的尴尬...

    本文将带领大家领略Spring事务的风采,Spring事务是我们在日常开发中经常会遇到的,也是各种大小面试中的高频题,希望通过本文,能让大家对Spring事务有个深入的了解,无论开发还是面试,都不会让 ...

  8. 浅谈:Spring Boot原理分析,切换内置web服务器,SpringBoot监听项目(使用springboot-admin),将springboot的项目打成war包

    浅谈:Spring Boot原理分析(更多细节解释在代码注释中) 通过@EnableAutoConfiguration注解加载Springboot内置的自动初始化类(加载什么类是配置在spring.f ...

  9. 浅谈 Spring IOC

    浅谈 Spring IOC 什么是IOC 理解 IOC 和 DI Spring IOC 相关操作个人总结 什么是IOC Ioc-Inversion of Control,即"控制反转&quo ...

最新文章

  1. qt 控件 背景色 透明 除去边框
  2. DedeHttpDown下载类
  3. SRM598 Div1
  4. android 相机 全功能,一加7系首个Android 11公测代码暗示了相机应用的诸多功能更新...
  5. 合作式智能运输系统 车用通信系统应用层及应用数据交互标准(第二阶段)_携手推进汽车与信息通信标准化融合发展,CSAE与CCSA签署标准化工作备忘录...
  6. 【干货】Html与CSS入门学习笔记12-14【完】
  7. C程序设计基础之多维数组的指针变量
  8. 极致CMS个人博客企业官网模板
  9. 广州的11个辖区_重庆前三季度GDP反超广州,这对两城到底意味着什么?
  10. 酷派COOL 20 Pro影像大升级:搭载5000万AI三摄 主攻夜景
  11. pytorch torch.ones
  12. ubuntu20.04 显卡驱动 cuda cudnn安装
  13. 子网划分,掩码转换计算
  14. 数学速算法_孩子数学计算老出错?复习阶段,家长赶紧和孩子一起找准原因!...
  15. 软件经验|GDAL空间数据开源库开发介绍
  16. 『中秋赏月』程序员用文心大模型带你玩转不一样的中秋
  17. 整数转罗马数字(C++)
  18. 以太坊白皮书(中英对照版)
  19. 钱,才是成年人活着的最大底气
  20. 循环队列(Circular Queue)

热门文章

  1. 记个SwitchButton笔记
  2. 短期逾期影响贷款吗?
  3. 现代企业三大目标才是核心
  4. 能搞垮你的不止是同行
  5. 现在人真的很奇怪,看见有钱人点头哈腰
  6. 如何看待0.5元可买到身份匹配的人脸数据?
  7. Qt——P10 自定义的信号和槽
  8. SQL Server Profiler概述
  9. 日历报表_在报表中实施不同的日历
  10. sql server 主键_SQL Server中人口过多的主键和CE模型的变化