事务的传播特性:
一张图很清楚的描述事务的传播特性:
- Required:当前有事务时使用当前的事务,当前没有事务时创建新的事务
实例
对不同的操作类型配置不同的传播类型
<aop:aspectj-autoproxy proxy-target-class="true"/>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"
no-rollback-for="com.carease.cms.common.ex.SimpleNoRollbackException"/>
<tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
<tx:method name="modify*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
<tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
<tx:method name="save*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
<tx:method name="upload*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
<tx:method name="do*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="noSupport*" propagation="NOT_SUPPORTED" read-only="true"/>
<tx:method name="*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
read-only=true的操作表示可以进行读操作不可以进行写操作;read-only=false表示可以进行读写操作。
将事务控制在service层:
<!--把事务控制在Service层-->
<aop:config>
<aop:pointcut id="pc" expression="execution(public * com.carease.cms.eps.biz.*.service.*.*(..))" />
<aop:advisor pointcut-ref="pc" advice-ref="txAdvice" />
</aop:config>
<bean id="transactionTemplate"
class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager" />
</bean>