在xml中配置
例子:
<!-- 1、 定义事务管理器的bean(需要注入dataSource) -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 2、 定义事务增强或事务通知(事务处理的代码,可以设置各个方法是否支持事务并配置事务属性) -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 定义事务属性,声明事务规则 -->
<tx:attributes>
<tx:method name="load" read-only="true"/>
<tx:method name="list" read-only="true"/>
<tx:method name="count" read-only="true"/>
<tx:method name="pager" read-only="true"/>
<tx:method name="insert" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<!-- NOT_SUPPORTED 不支持事务 -->
<tx:method name="trans00" propagation="NOT_SUPPORTED"/>
<tx:method name="init" propagation="NOT_SUPPORTED"/>
<tx:method name="trans01" propagation="NOT_SUPPORTED"/>
<!-- REQUIRED 支持事务 -->
<tx:method name="trans02" propagation="REQUIRED"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 3、 aop配置:advisor切面————表示哪些包的哪些类的哪些方法,需要添加事务增加 -->
<aop:config proxy-target-class="true">
<!-- 定义切入点:包类方法 -->
<aop:pointcut id="serviceMethod" expression="execution(* edu.uc.service..*.*(..))"/>
<!-- 将切入点组合与事务通知 -->
<aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice"/>
</aop:config>
在使用时 抛出异常 RuntimeException(e),数据回滚
throw new RuntimeException(e)
更正:
<!-- 去掉原来的2、3步骤,添加下面的第四步骤 -->
<!-- 4.开启事务的注解驱动 -->
<!-- transaction-manager属性的值为前面定义的事务管理器的id或名称 -->
<!-- 如果事务管理器的id 或名称为transactionManager,则可以不写transaction-manager属性 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
接着在需要事务处理的方法加上@Transactional
eg.
@Transactional(propagation = Propagation.REQUIRED)
public Long trans02(Long userA, Long userB, Long money) {}