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. Code Review Tools

    Code Review中文应该译作“代码审查”或是“代码评审”,这是一个流程,当开发人员写好代码后,需要让别人来review一下他的代码,这是一种有效发现BUG的方法.由此,我们可以审查代码的风格.逻 ...

  2. maven不打包子模块资源文件

    在maven多模块项目中,对子模块中的测试文件不需要打包到目标项目中,以免产生影响.实现方法: 1. 将测试资源放在java/test/resources 目录下,mvn package默认不会将te ...

  3. js或者ext js获取返回值

      由于前台业务需要在判断中发起ajax到后台,根据返回值校验是否通过 代码如下 关键点在于要将async关闭 设置成同步,这样才能接收到要返回的flag                       ...

  4. CLR via C# 3rd - 05 - Primitive, Reference, and Value Types

    1. Primitive Types        Any data types the compiler directly supports are called primitive types. ...

  5. This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes.

    -- :::] This application is modifying the autolayout engine from a background thread, which can lead ...

  6. Spark RDD API详解(一) Map和Reduce

    RDD是什么? RDD是Spark中的抽象数据结构类型,任何数据在Spark中都被表示为RDD.从编程的角度来看,RDD可以简单看成是一个数组.和普通数组的区别是,RDD中的数据是分区存储的,这样不同 ...

  7. Bash Shell内建命令和保留字

    Bash Shell内建命令和保留字命令含义!保留字,逻辑非:不做任何事,只做参数展开.读取文件并在shell中执行它alias设置命令或命令行别名bg将作业置于后台运行bind将关键字序列与read ...

  8. unsigned char 类型

    在蓝牙4.0的开发中,很多数据类型都用到了 unsigned char ,我觉得用这个类型的一个原因是相比较于整型,它占的空间更少. 比如: unsigned char a = 1;  // 占1个字 ...

  9. Flat UI 工具包

    Flat UI是一套精美的扁平风格 UI 工具包,基于 Twitter Bootstrap 实现.这套界面工具包含许多基本的和复杂的 UI 部件,例如按钮,输入框,组合按钮,复选框,单选按钮,标签,菜 ...

  10. POJ做题笔记:1000,1004,1003

    1000 A+B Problem 题目大意:输入两个数a和b,输出他们的和. 代码: #include <stdio.h> int main() { int a, b; while (sc ...