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. Android SDK ADT下载地址

    http://dl.google.com/android/android-sdk_rXX-windows.zip http://dl.google.com/android/ADT-X.X.X.zip ...

  2. Installshield调用DLL的正确姿势

    脚本如下 szDllPath = SUPPORTDIR ^ "TestCom.dll";       set oMyTest = CoCreateObjectDotNet(szDl ...

  3. Nginx Debug Log

    //检查nginx.conf时(sudo ./nginx -t),输出数据到检测结果 //ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "配置解析处理&q ...

  4. Egit Patch

    Git为我们提供了Patch功能,Patch中包含了源码更改的描述,能够应用于其他Eclipse工作空间或者Git仓库.也就是说,可以将当前提交导出至其他分支或者项目中.   举个例子,项目A.B中使 ...

  5. eclipse中安装Open Explorer

    刚刚解压的eclipse中一般没有下面如图所示的这个操作,不能快速进入所选中的文件在Windows资源管理器所在的目录 我们需要下载OpenExplorer.jar包,放到eclipse解压后的dro ...

  6. jQuery中的Ajax几种请求方法

    在网上查的几种Ajax的请求的方法: jQuery 确实是一个挺好的轻量级的JS框架,能帮助我们快速的开发JS应用,并在一定程度上改变了我们写JavaScript代码的习惯.废话少说,直接进入正题,我 ...

  7. MySQL ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO) 的解决办法和原因

    这两天下载了MySQL5.7.11进行安装,发现到了初次使用输入密码的时候,不管怎样都进不去,即使按照网上说的在mysqld 下面添加skip-grant-tables也是不行,后来研究了两天,终于找 ...

  8. jQuery高级编程

    jquery高级编程1.jquery入门2.Javascript基础3.jQuery核心技术 3.1 jQuery脚本的结构 3.2 非侵扰事JavaScript 3.3 jQuery框架的结构 3. ...

  9. webpack es6 to es5支持配置

    1. 安装webpack npm install webpack --save-dev 2. 安装babel  实现 ES6 到 ES5 npm install --save-dev babel-co ...

  10. Python之路,day6-Python基础

    1.config 模块 import configparser conf = configparser.ConfigParser() conf[', 'Compression': 'yes', '} ...