文章目录
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
不管是否存在事务,都创建一个新的事务。如果已经存在一个事