声明式事务--Spring注解
使用方法如下:
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW,timeout = 10)
声明式事务--xml配置
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes> <!--设置所有匹配的方法,然后设置传播级别和事务隔离-->
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="create*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="merge*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="put*" propagation="REQUIRED" />
<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
<tx:method name="count*" propagation="SUPPORTS" read-only="true" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
<tx:method name="list*" propagation="SUPPORTS" read-only="true" />
<tx:method name="*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* org.transaction..service.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
</aop:config>
事务的传播机制
所谓事务传播机制,也就是在事务在多个方法的调用中是如何传递的,是重新创建事务还是使用父方法的事务?父方法的回滚对子方法的事务是否有影响?这些都是可以通过事务传播机制来决定的。
申明式事务注解的传播属性用法如下:
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
Spring在TransactionDefinition接口中定义了七个事务传播行为:
- REQUIRED:如果当前没有事务,就新建一个事务,如果已存在一个事务中,加入到这个事务中。(默认属性)
- SUPPORTS:支持当前事务,如果没有当前事务,就以非事务方法执行。
- MANDATORY:使用当前事务,如果没有当前事务,就抛出异常。
- REQUIRES_NEW:新建事务,如果当前存在事务,把当前事务挂起。
- NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
- NEVER:以非事务方式执行操作,如果当前事务存在则抛出异常。
- NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与propagation_required类似的操作。
说明,当使用Propagation.REQUIRES_NEW在子方法中新建事务时,子方法必须是在另一个Service下,在当前Service下无法生效。
编程式事务
编程式事务即为手动事务管理