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. java 对象 :创建

    灵感来自effective java 关于对象,是java的核心,如何有效的创建其实是一个值得关注的地方. 1.静态工厂:这是一个值得关注的,并且应该时刻考虑的方法. 优点:1.他是有名字的,这个是如 ...

  2. Magento代码之订单创建流程

    Magento代码之订单创建流程         直接看代码吧.下面的代码是如何通过程序创建一个完美订单.        <?php        require_once 'app/Mage. ...

  3. UIView---汇总

    视图.绘图.贴图.手势.变形.布局.动画.动力.特效 UIBezierPath.UIGestureRecognizer.CGAffineTransform.frame.bounds.center.tr ...

  4. 判断IP地址的类型

    #include <stdio.h> #include <stdlib.h> void main() { ]; int ip_addr; printf("请输入IP地 ...

  5. 《深入浅出Node.js》第6章 理解 Buffer

    @by Ruth92(转载请注明出处) 第6章 理解 Buffer ✁ 为什么需要 Buffer? 在 Node 中,应用需要处理网络协议.操作数据库.处理图片.接收上传文件等,在网络流和文件的操作中 ...

  6. JSTL的fn函数

    JSTL使用表达式来简化页面的代码,这对一些标准的方法,例如bean的getter/setter方法,请求参数或者context以及session中的数据的访问非常方便,但是我们在实际应用中经常需要在 ...

  7. linux grep,sed,awk和diff的使用

    1:grep//显示行 # grep 'main' /home/myhome/a.c//将a.c含有main的行显示出来 # grep -v 'main' /home/myhome/a.c //显示除 ...

  8. 过滤emoji表情

    str=str.replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g, "");

  9. php-长文章分页函数

    <?php function ff_page($content,$page) { global $expert_id; $PageLength = 2000; //每页字数 $CLength = ...

  10. connections

    recv(), recvfrom() http://lxr.free-electrons.com/source/net/socket.c http://grepcode.com/file/reposi ...