一、Spring声明式事务管理属性
-- @Transactional注解属性
1、事务传播行为【Propagation】
当事务方法被另一个事务方法调用时,必须指定事务应该如何传播;
比方说:执行事务方法method1之后,调用事务方法method2,此时需要设置method2方法的事务传播行为。
在Spring中,给我们提供了七种传播方式,其中最常用的有以下两种:
/**
* Support a current transaction, create a new one if none exists.
* Analogous to EJB transaction attribute of the same name.
* <p>This is the default setting of a transaction annotation.
*/
REQUIRED(TransactionDefinition.PROPAGATION_REQUIRED),
/**
* Create a new transaction, and suspend the current transaction if one exists.
* Analogous to the EJB transaction attribute of the same name.
* <p><b>NOTE:</b> Actual transaction suspension will not work out-of-the-box
* on all transaction managers. This in particular applies to
* {@link org.springframework.transaction.jta.JtaTransactionManager},
* which requires the {@code javax.transaction.TransactionManager} to be
* made available to it (which is server-specific in standard Java EE).
* @see org.springframework.transaction.jta.JtaTransactionManager#setTransactionManager
*/
REQUIRES_NEW(TransactionDefinition.PROPAGATION_REQUIRES_NEW),
以上为两种枚举类型的源代码,分别说明下:分别为required和requireds_new两种,本文着重讲解这两种;
required:如果当前有事务在运行,当前的方法就在这个事务内运行;否则就启动一个新的事务,并在自己的事务内运行;
用法特点:
@Transactional(propagation = Propagation.REQUIRED)
在使用时,不用特意声明,required为默认枚举;使用后所有事务都统一在一个事务内。
requireds_new:当前的必须启动新事务,并在自己的事务内运行,如果有事务正在运行,应该将它挂起;
@Transactional(propagation = Propagation.REQUIRES_NEW)
使用后,在当前代码块或方法中开启一个新事务,是否回滚取决于本次业务处理逻辑;
2、使用场景:
required:买书场景->当余额不足时,一本书也不允许买;
requireds_new:买书场景->当余额不足时,不买最后一本导致余额不足的书;