mybitis事务管理

1. myBatis单独使用时,使用SqlSession来处理事务 : 
原文:http://czj4451.iteye.com/blog/2037759
Java代码   收藏代码
  1. public class MyBatisTxTest {  
  2.   
  3.     private static SqlSessionFactory sqlSessionFactory;  
  4.     private static Reader reader;  
  5.   
  6.     @BeforeClass  
  7.     public static void setUpBeforeClass() throws Exception {  
  8.         try {  
  9.             reader = Resources.getResourceAsReader("Configuration.xml");  
  10.             sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);  
  11.         } finally {  
  12.             if (reader != null) {  
  13.                 reader.close();  
  14.             }  
  15.         }  
  16.     }  
  17.       
  18.     @Test  
  19.     public void updateUserTxTest() {  
  20.         SqlSession session = sqlSessionFactory.openSession(false); // 打开会话,事务开始  
  21.           
  22.         try {  
  23.             IUserMapper mapper = session.getMapper(IUserMapper.class);  
  24.             User user = new User(9"Test transaction");  
  25.             int affectedCount = mapper.updateUser(user); // 因后面的异常而未执行commit语句  
  26.             User user = new User(10"Test transaction continuously");  
  27.             int affectedCount2 = mapper.updateUser(user2); // 因后面的异常而未执行commit语句  
  28.             int i = 2 / 0// 触发运行时异常  
  29.             session.commit(); // 提交会话,即事务提交  
  30.         } finally {  
  31.             session.close(); // 关闭会话,释放资源  
  32.         }  
  33.     }  
  34. }  


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

a.  @Transactional 方式: 

在类路径下创建beans-da-tx.xml文件,在beans-da.xml(系列五)的基础上加入事务配置: 
Xml代码   收藏代码
  1. <!-- 事务管理器 -->  
  2. <bean id="txManager"  
  3.     class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  4.         <property name="dataSource" ref="dataSource" />  
  5. </bean>  
  6.   
  7. <!-- 事务注解驱动,标注@Transactional的类和方法将具有事务性 -->  
  8. <tx:annotation-driven transaction-manager="txManager" />  
  9.   
  10. <bean id="userService" class="com.john.hbatis.service.UserService" />  


服务类: 
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. }  


在测试类中加入: 
Java代码   收藏代码
  1. @RunWith(SpringJUnit4ClassRunner.class)  
  2. @ContextConfiguration(locations = { "classpath:beans-da-tx.xml" })  
  3. public class SpringIntegrateTxTest {  
  4.   
  5.     @Resource  
  6.     UserService userService;  
  7.   
  8.     @Test  
  9.     public void updateUsersExceptionTest() {  
  10.         userService.batchUpdateUsersWhenException();  
  11.     }  
  12.   
  13.     @Test  
  14.     public void txUpdateUsersExceptionTest() {  
  15.         userService.txUpdateUsersWhenException();  
  16.     }  
  17. }  


b.  TransactionTemplate 方式 

在beans-da-tx.xml中添加: 
Xml代码   收藏代码
  1. <bean id="txTemplate" class="org.springframework.transaction.support.TransactionTemplate">  
  2.     <constructor-arg type="org.springframework.transaction.PlatformTransactionManager" ref="transactionManager" />  
  3. </bean>  


在UserService类加入: 
Java代码   收藏代码
  1. @Autowired(required = false)  
  2. TransactionTemplate txTemplate;  
  3.   
  4. public int txUpdateUsersWhenExceptionViaTxTemplate() {  
  5.     int retVal = txTemplate.execute(new TransactionCallback<Integer>() {  
  6.   
  7.         @Override  
  8.         public Integer doInTransaction(TransactionStatus status) { // 事务操作  
  9.             User user = new User(9"Before exception");  
  10.             int affectedCount = mapper.updateUser(user); // 因后面的异常而回滚  
  11.             User user2 = new User(10"After exception");  
  12.             int i = 1 / 0// 抛出运行时异常并回滚  
  13.             int affectedCount2 = mapper.updateUser(user2); // 未执行  
  14.             if (affectedCount == 1 && affectedCount2 == 1) {  
  15.                 return 1;  
  16.             }  
  17.             return 0;  
  18.         }  
  19.           
  20.     });  
  21.     return retVal;  
  22. }  


在SpringIntegrateTxTest类中加入: 
Java代码   收藏代码
  1. @Test  
  2. public void updateUsersWhenExceptionViaTxTemplateTest() {  
  3.     userService.txUpdateUsersWhenExceptionViaTxTemplate(); //   
  4. }  


注: 不可catch ExceptionRuntimeException而不抛出 : 
Java代码   收藏代码
  1. @Transactional  
  2. public int txUpdateUsersWhenExceptionAndCatch() { // 事务性操作,但是外围框架捕获不到异常,认为执行正确而提交。  
  3.     try {  
  4.         User user = new User(9"Before exception");  
  5.         int affectedCount = mapper.updateUser(user); // 执行成功  
  6.         User user2 = new User(10"After exception");  
  7.         int i = 1 / 0// 抛出运行时异常  
  8.         int affectedCount2 = mapper.updateUser(user2); // 未执行  
  9.         if (affectedCount == 1 && affectedCount2 == 1) {  
  10.             return 1;  
  11.         }  
  12.     } catch (Exception e) { // 所有异常被捕获而未抛出  
  13.         e.printStackTrace();  
  14.     }  
  15.     return 0;  
  16. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值