文章目录
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
不管是否存在事务,都创

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

被折叠的 条评论
为什么被折叠?



