1. myBatis单独使用时,使用SqlSession来处理事务:

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

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

a. @Transactional方式:

在类路径下创建beans-da-tx.xml文件,在beans-da.xml(系列五)的基础上加入事务配置:

  1. <!-- 事务管理器 -->
  2. <bean id="txManager"
  3. class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  4. <property name="dataSource" ref="dataSource" />
  5. </bean>
  6. <!-- 事务注解驱动,标注@Transactional的类和方法将具有事务性 -->
  7. <tx:annotation-driven transaction-manager="txManager" />
  8. <bean id="userService" class="com.john.hbatis.service.UserService" />

服务类:

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

在测试类中加入:

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration(locations = { "classpath:beans-da-tx.xml" })
  3. public class SpringIntegrateTxTest {
  4. @Resource
  5. UserService userService;
  6. @Test
  7. public void updateUsersExceptionTest() {
  8. userService.batchUpdateUsersWhenException();
  9. }
  10. @Test
  11. public void txUpdateUsersExceptionTest() {
  12. userService.txUpdateUsersWhenException();
  13. }
  14. }

b. TransactionTemplate方式

在beans-da-tx.xml中添加:

  1. <bean id="txTemplate" class="org.springframework.transaction.support.TransactionTemplate">
  2. <constructor-arg type="org.springframework.transaction.PlatformTransactionManager" ref="transactionManager" />
  3. </bean>

在UserService类加入:

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

在SpringIntegrateTxTest类中加入:

  1. @Test
  2. public void updateUsersWhenExceptionViaTxTemplateTest() {
  3. userService.txUpdateUsersWhenExceptionViaTxTemplate(); //
  4. }

注:不可catch Exception或RuntimeException而不抛出

    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. }

myBatis之事务管理的更多相关文章

  1. spring boot配置mybatis和事务管理

    spring boot配置mybatis和事务管理 一.spring boot与mybatis的配置 1.首先,spring boot 配置mybatis需要的全部依赖如下: <!-- Spri ...

  2. Spring Boot -- Spring Boot之@Async异步调用、Mybatis、事务管理等

    这一节将在上一节的基础上,继续深入学习Spring Boot相关知识,其中主要包括@Async异步调用,@Value自定义参数.Mybatis.事务管理等. 本节所使用的代码是在上一节项目代码中,继续 ...

  3. SpringMVC+MyBatis整合——事务管理

    项目一直没有做事务管理,这几天一直在想着解决这事,今天早上终于解决了.接下来直接上配置步骤. 我们项目采用的基本搭建环境:SpringMVC.MyBatis.Oracle11g.WebLogic10. ...

  4. Spring 与 mybatis整合---事务管理

    MyBatis与Spring整合前后事务管理有所区别 整合前:通过 session = sessionFactory.openSession(true); //或者是false 设置事务是否自动提交: ...

  5. Spring+JTA+Atomikos+mybatis分布式事务管理

    我们平时的工作中用到的Spring事务管理是管理一个数据源的.但是如果对多个数据源进行事务管理该怎么办呢?我们可以用JTA和Atomikos结合Spring来实现一个分布式事务管理的功能.了解JTA可 ...

  6. Mybatis-学习笔记(6)Mybatis的事务管理机制

    1.什么是事务. 多个数据库原子访问应该被绑定成一个整体,这就是事务.事务是一个最小的逻辑执行单元,整个事务不能分开执行,要么同时执行,要么同时放弃执行. 事务的4个特性:原子性.一致性.隔离性.持续 ...

  7. SpringBoot 集成MyBatis、事务管理

    集成MyBatis (1)在pom.xml中添加依赖 <!-- mybatis的起步依赖.包含了mybatis.mybatis-spring.spring-jdbc(事务要用到)的坐标 --&g ...

  8. MyBatis+Spring 事务管理

                 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://kinglixing.blog.51cto.com/34 ...

  9. Spring Transaction + MyBatis SqlSession事务管理机制[marked]

随机推荐

  1. linux动态时钟探索

    在早期的linux内核版本的时间概念都是由周期时钟提供的.虽然比较有效,但是,对于关注能耗电量的系统上,就不能满足长时间休眠的需求,因为周期系统要求必须在一定的频率下,周期性的处于活动状态.因此,li ...

  2. WIN32服务程序(二):卸载服务

    卸载服务的过程是这样的,用OpenSCManager打开SCM,使用OpenService打开准备卸载的服务,通过QueryServiceStatus查询该服务的状态是否停止,如果否,则先停止该服务C ...

  3. [WPF]GridView或DataGrid中自定义样式:依据某一列设定其对应行的样式(背景色,字体等)

    附效果照一张: 本方法使用StyleSelector来 获得依据自定义逻辑的style. ① class ConditionalStyleSelector : StyleSelector { publ ...

  4. POJ 2653

    题目大意:一个小孩不断往地上扔棍子,共n根,求结束后共有多少根不与去他相交. 解法思路:典型的判断线段相交问题,利用快速排斥+双跨立判断相交,最后输出没相交的. (图片来源:http://www.2c ...

  5. 转发一篇C++编译器环境搭建的文章

    一.环境配置 1.  下载安装MinGW      地址  http://sourceforge.net/projects/mingw/ 2.  设置环境变量            在path变量中, ...

  6. 腾讯优测优分享 | Android适配中的一些特殊情况小结

    腾讯优测是专业的自动化测试平台,提供全面兼容适配测试,远程真机租用等多维度的测试服务! 作为一名"艰苦卓绝"的软件工程师,我在开发路上经常被各种奇葩情况虐的体无完肤...今天就想与 ...

  7. SDWebImageManager.m:244:22: Too many arguments to function call, expected 0,have 5

    SDWebImageManager.m:244:22: Too many arguments to function call, expected 0,have 5选中项目 Build Setting ...

  8. HTML5上传图片到ASP.NET.MVC

    @{ ViewBag.Title = "Home Page";} <!DOCTYPE HTML PUBLIC><html><head> < ...

  9. SSH(Struts,Spring,Hibernate)和SSM(SpringMVC,Spring,MyBatis)之间区别

    http://m.blog.csdn.net/article/details?id=52795914#0-qzone-1-52202-d020d2d2a4e8d1a374a433f596ad1440

  10. Mongodb和Hive详细对比

    本文主要用于分析在大数据场景下Mongodb和Hive的优缺点: 支持的数据类型 支持的查询 支持的数据量 性能优化手段