|
第一种 注解的方式实现声明式事务管理
<!-- 定义事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 开启事务控制的注解支持 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
@Transactional
public class MyBatisServiceImpl implements MyBatisService {
@Autowired
private MyBatisDao dao;
@Override
public void insert(Test test) {
dao.insert(test);
//抛出unchecked异常,触发事物,回滚
throw new RuntimeException("test");
}
第二种 如何通过面向切面的方式实现事务管理
<!-- 定义事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务管理增强 -->
<!-- 配置事务管理增强 需要指定一个事物管理器-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" propagation="SUPPORTS" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<!-- 定义切面 -->
<aop:config>
<!-- 定义切入点,及切入点的表达式 和id -->
<aop:pointcut id="serviceMethod"
expression="execution(* cn.kgc.service..*.*(..))" />
<!-- 把增强的引用和切入点的引用组合起来-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod" />
</aop:config>
|