mybatic与spring结合的事务管理

原文地址:http://czj4451.iteye.com/blog/2037759

 

mybatis与spring结合后,事务管理更加方便,这里介绍使用transactionnal的方式,有错的的地方,希望大家指出。

1. 和Spring集成后,使用Spring的事务管理: 

a. @Transactional方式: 

在类路径下创建beans-da-tx.xml文件,在applicationContext-resources.xml的基础上加入事务配置: 

Xml代码   收藏代码
  1. <!-- 配置事务管理器,注意这里的dataSource和SqlSessionFactoryBean的dataSource要一致,不然事务就没有作用了 -->
    <bean id="transactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
    </bean>

  2.  

    <tx:annotation-driven transaction-manager="transactionManager" /><!-- 事务注解驱动,标注@Transactional的类和方法将具有事务性 --> 



服务类: 

Java代码   收藏代码
    1. @Service("userService")  
    2. public class UserService {  
    3.   
    4.     @Autowired  
    5.     IUserMapper mapper;  
    6.   
    7.     public int batchUpdateUsersWhenException() { // 非事务性  
    8.         User user = new User(9, "Before exception");  
    9.         int affectedCount = mapper.updateUser(user); // 执行成功  
    10.         User user2 = new User(10, "After exception");  
    11.         int i = 1 / 0; // 抛出运行时异常  
    12.         int affectedCount2 = mapper.updateUser(user2); // 未执行  
    13.         if (affectedCount == 1 && affectedCount2 == 1) {  
    14.             return 1;  
    15.         }  
    16.         return 0;  
    17.     }  
    18.   
    19.     @Transactional  
    20.     public int txUpdateUsersWhenException() { // 事务性  
    21.         User user = new User(9, "Before exception");  
    22.         int affectedCount = mapper.updateUser(user); // 因后面的异常而回滚  
    23.         User user2 = new User(10, "After exception");  
    24.         int i = 1 / 0; // 抛出运行时异常,事务回滚  
    25.         int affectedCount2 = mapper.updateUser(user2); // 未执行  
    26.         if (affectedCount == 1 && affectedCount2 == 1) {  
    27.             return 1;  
    28.         }  
    29.         return 0;  
    30.     }  
    31. }  

转载于:https://www.cnblogs.com/dylenwu/p/6128537.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值