从@Transactional看事务的传播和隔离

本文深入探讨了Spring中的事务管理,包括transactionManager的选择、事务的传播行为(如REQUIRED、SUPPORTS、REQUIRES_NEW等)、隔离级别(如READ_COMMITTED、SERIALIZABLE等)以及timeout和readOnly属性的设定。同时,提到了事务失效的常见场景,如非public方法、嵌套事务和异常处理策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

spring如何处理事务呢?下面是个伪代码示意:

	  begin Transactional;
       try{
   
           //TODO
           commit;
       }catch (Throwable e){
   
           if(e属于该提交的(即noRollbackFor指定)的异常类型){
   
               commit;
           }else {
   
               rollback;
           }
       }

1. transactionManager 当在配置文件中有多个TransactionManager,可以用该属性指定使用哪个事务管理器

如果要配置全局事务管理,参考这篇文章全局性事务控制如何在springboot中配置

2. 事务的传播行为(propagation) ,默认值为REQUIRED

  • Propagation.REQUIRED
    默认传播行为 如果有事务那么加入此事务,没有就新建一个事务
	/**
	 * Support a current transaction, create a new one if none exists.
	 * <p>This is the default setting of a transaction annotation.
	 */
  • Propagation.SUPPORTS
    如果其他bean调用这个方法,在其他bean中声明了事务那么久加入事务,如果其他bean中没有声明事务就不用事务
	/**
	 * Support a current transaction, execute non-transactionally if none exists.
	 * <p>Note: For transaction managers with transaction synchronization,
	 * PROPAGATION_SUPPORTS is slightly different from no transaction at all,
	 * as it defines a transaction scope that synchronization will apply for.
	 * As a consequence, the same resources (JDBC Connection, Hibernate Session, etc)
	 * will be shared for the entire specified scope. Note that this depends on
	 * the actual synchronization configuration of the transaction manager.
	 */
  • Propagation.REQUIRES_NEW
    不管是否存在事务,都创建一个新的事务。如果已经存在一个事
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值