`

myBatis系列之七:事务管理

阅读更多
myBatis系列之一:搭建开发环境
myBatis系列之二:以接口方式交互数据
myBatis系列之三:增删改查
myBatis系列之四:关联数据的查询
myBatis系列之五:与Spring3集成
myBatis系列之六:与SpringMVC集成


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

public class MyBatisTxTest {

	private static SqlSessionFactory sqlSessionFactory;
	private static Reader reader;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		try {
			reader = Resources.getResourceAsReader("Configuration.xml");
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		} finally {
			if (reader != null) {
				reader.close();
			}
		}
	}
	
	@Test
	public void updateUserTxTest() {
		SqlSession session = sqlSessionFactory.openSession(false); // 打开会话,事务开始
		
		try {
			IUserMapper mapper = session.getMapper(IUserMapper.class);
			User user = new User(9, "Test transaction");
			int affectedCount = mapper.updateUser(user); // 因后面的异常而未执行commit语句
			User user = new User(10, "Test transaction continuously");
			int affectedCount2 = mapper.updateUser(user2); // 因后面的异常而未执行commit语句
			int i = 2 / 0; // 触发运行时异常
			session.commit(); // 提交会话,即事务提交
		} finally {
			session.close(); // 关闭会话,释放资源
		}
	}
}


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

a. @Transactional方式:

在类路径下创建beans-da-tx.xml文件,在beans-da.xml(系列五)的基础上加入事务配置:
  <!-- 事务管理器 -->
  <bean id="txManager"
  	class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  		<property name="dataSource" ref="dataSource" />
  </bean>
  
  <!-- 事务注解驱动,标注@Transactional的类和方法将具有事务性 -->
  <tx:annotation-driven transaction-manager="txManager" />

  <bean id="userService" class="com.john.hbatis.service.UserService" />


服务类:
@Service("userService")
public class UserService {

	@Autowired
	IUserMapper mapper;

	public int batchUpdateUsersWhenException() { // 非事务性
		User user = new User(9, "Before exception");
		int affectedCount = mapper.updateUser(user); // 执行成功
		User user2 = new User(10, "After exception");
		int i = 1 / 0; // 抛出运行时异常
		int affectedCount2 = mapper.updateUser(user2); // 未执行
		if (affectedCount == 1 && affectedCount2 == 1) {
			return 1;
		}
		return 0;
	}

	@Transactional
	public int txUpdateUsersWhenException() { // 事务性
		User user = new User(9, "Before exception");
		int affectedCount = mapper.updateUser(user); // 因后面的异常而回滚
		User user2 = new User(10, "After exception");
		int i = 1 / 0; // 抛出运行时异常,事务回滚
		int affectedCount2 = mapper.updateUser(user2); // 未执行
		if (affectedCount == 1 && affectedCount2 == 1) {
			return 1;
		}
		return 0;
	}
}


在测试类中加入:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:beans-da-tx.xml" })
public class SpringIntegrateTxTest {

	@Resource
	UserService userService;

	@Test
	public void updateUsersExceptionTest() {
		userService.batchUpdateUsersWhenException();
	}

	@Test
	public void txUpdateUsersExceptionTest() {
		userService.txUpdateUsersWhenException();
	}
}


b. TransactionTemplate方式

在beans-da-tx.xml中添加:
  <bean id="txTemplate" class="org.springframework.transaction.support.TransactionTemplate">
  	<constructor-arg type="org.springframework.transaction.PlatformTransactionManager" ref="transactionManager" />
  </bean>


在UserService类加入:
@Autowired(required = false)
TransactionTemplate txTemplate;

public int txUpdateUsersWhenExceptionViaTxTemplate() {
	int retVal = txTemplate.execute(new TransactionCallback<Integer>() {

		@Override
		public Integer doInTransaction(TransactionStatus status) { // 事务操作
			User user = new User(9, "Before exception");
			int affectedCount = mapper.updateUser(user); // 因后面的异常而回滚
			User user2 = new User(10, "After exception");
			int i = 1 / 0; // 抛出运行时异常并回滚
			int affectedCount2 = mapper.updateUser(user2); // 未执行
			if (affectedCount == 1 && affectedCount2 == 1) {
				return 1;
			}
			return 0;
		}
		
	});
	return retVal;
}


在SpringIntegrateTxTest类中加入:
@Test
public void updateUsersWhenExceptionViaTxTemplateTest() {
	userService.txUpdateUsersWhenExceptionViaTxTemplate(); // 
}


注:不可catch ExceptionRuntimeException而不抛出
@Transactional
public int txUpdateUsersWhenExceptionAndCatch() { // 事务性操作,但是外围框架捕获不到异常,认为执行正确而提交。
	try {
		User user = new User(9, "Before exception");
		int affectedCount = mapper.updateUser(user); // 执行成功
		User user2 = new User(10, "After exception");
		int i = 1 / 0; // 抛出运行时异常
		int affectedCount2 = mapper.updateUser(user2); // 未执行
		if (affectedCount == 1 && affectedCount2 == 1) {
			return 1;
		}
	} catch (Exception e) { // 所有异常被捕获而未抛出
		e.printStackTrace();
	}
	return 0;
}
分享到:
评论
1 楼 陌上君 2016-08-09  
引用
[lis[color=indigo][/color]t]
  • [img][/img]
  • [/list]

    相关推荐

      走进MyBatis世界之基础入门(二)

      MyBatis是一款优秀的ORM...本章主要内容:MyBatis与Spring如何集成,声明式事务管理,MapperScannerConfigurer本次课程,在YY上进行,YY频道:71042615课程回放:http://bbs.51cto.com/open/do/course/cid/65系列课程:...

      springmybatis

      mybatis实战教程mybatis in action之七实现mybatis分页源码下载 mybatis实战教程mybatis in action之八mybatis 动态sql语句 mybatis实战教程mybatis in action之九mybatis 代码生成工具的使用 mybatis ...

      金融贷款p2p项目源码.rar

      事务管理:MySQL事务处理  .... 设计工具 : 工具名称 版本 用途说明 ERwin 用来进行数据库对象的设计 Word 2007 用来进行设计类文档的编写,如架构文档。 编码工具 : 工具名称 版本 用途说明 ...

      黑马49期全系列包括品优购

      freemarker 单点登录:cas 权限管理:SpringSecurity, 跨域:cros 支付:微信扫描 短信验证:阿里大于 密码加密:BCrypt 富文本:KindEditor 事务:声明式事务 任务调度:spring task,有问题请留言

      基于SpringBoot + Mybatis + Thymeleaf 商品管理系统.zip

      基于SpringBoot + Mybatis + Thymeleaf + Redis + MongoDB + MySQL开发的 MySQL 是一款广受欢迎的开源关系型数据库管理系统(RDBMS),由瑞典MySQL AB公司开发,现隶属于美国甲骨文公司(Oracle)。自1998年首次...

      JAVA中spring介绍以及个人使用心得

      事务管理:Spring框架提供了强大的事务管理支持,可以通过编程式事务管理或声明式事务管理来管理应用程序中的事务。 MVC框架:Spring框架提供了一个灵活的MVC框架,可以帮助开发人员构建Web应用程序。该框架支持...

      基于SSM+Mysql的企业人力资源管理系统.zip

      基于SSM+MySQL的企业人力资源管理系统是一个用于企业内部人力资源管理的综合平台。...同时,Spring框架提供了依赖注入、事务管理等功能,简化了系统的开发和维护工作,增强了系统的可扩展性和稳定性。

      ssm班级事务管理系统.zip

      这些项目采用Java语言和SSM框架,是一系列功能丰富的系统。无论是在线考试、医院分诊管理,还是线上会议、志愿者服务平台,或者是学生请假管理、网约车用户服务平台,这些项目都充分利用了SSM框架的优势,为用户提供...

      2023年基于 SpringBoot + Vue + ElementUI 的人力资源管理系统(附源码,包含数据库文件)

      本系统主要分四个模块,分别是系统管理和权限管理、薪资管理、考勤管理,系统管理主要用于日常事务管理管理,权限管理,用于控制员工的访问权限,薪资管理主要是对员工的五险一金以及社保数据的修改和添加,考勤管理...

      该项目设计了基于SpringBoot+Mybatis框架的私人影院预约系统.zip

      包含Mybatis、Springboot、Shiro、MD5、Thymeleaf、MySQL、Layui等相关技术。 MySQL 是一款广受欢迎的开源关系型数据库管理系统(RDBMS),由瑞典MySQL AB公司开发,现隶属于美国甲骨文公司(Oracle)。自1998年...

      springboot+mybatis+dubbo 本项目是基于微服务架构的班车预约系统.zip

      采用两个版本第一个版本:springboot+mybatis+dubbo+rocketmq+mysql+redis等。第二个版 MySQL 是一款广受欢迎的开源关系型数据库管理系统(RDBMS),由瑞典MySQL AB公司开发,现隶属于美国甲骨文公司(Oracle)。自...

      基于SSM+Mysql的期末考试考务管理系统wlw.zip

      基于SSM+MySQL的期末考试考务管理系统是一个用于高校或学院管理期末考试过程的在线平台。...同时,Spring框架提供了依赖注入、事务管理等功能,简化了系统的开发和维护工作,增强了系统的可扩展性和稳定性。

      基于SSM框架个性化影片推荐系统.zip

      Spring还提供了一系列服务和设计模式的实现,如事务管理、安全性、JDBC操作等。 2. **Spring MVC**: 作为Spring的一个模块,Spring MVC是一个模型-视图-控制器(MVC)的Web框架,用于构建Web应用程序。它提供了一种...

      java源码期末大作业基于ssm的孩童收养信息管理+vue(源码+说明文档+lw).rar

      该系统结合了后端的SSM(Spring+Spring MVC+MyBatis)框架和前端的Vue.js技术,实现了从孩童登记管理、收养申请审批、收养家庭管理到收养流程跟踪等一系列功能,为相关部门提供了便捷高效的信息管理工具,确保了收养...

      基于SpringBoot + Mybatis + Thymeleaf + MySQL开发的购书商城系统.zip

      自1998年首次发布以来,MySQL以其卓越的性能、可靠性和可扩展性,成为全球范围内Web应用程序、企业级解决方案以及其他各种数据处理场景的首选数据库平台之一。 以下是对MySQL数据库的详细介绍: 核心特性与优势 ...

      基于SpringBoot+Mybatis+MySql+thyemleaf的个人博客系统设计与实现.zip

      自1998年首次发布以来,MySQL以其卓越的性能、可靠性和可扩展性,成为全球范围内Web应用程序、企业级解决方案以及其他各种数据处理场景的首选数据库平台之一。 以下是对MySQL数据库的详细介绍: 核心特性与优势 ...

      基于SpringBoot+Redis+Mybatis+MySQL+RabbitMQ技术的仿大众点评项目.zip

      自1998年首次发布以来,MySQL以其卓越的性能、可靠性和可扩展性,成为全球范围内Web应用程序、企业级解决方案以及其他各种数据处理场景的首选数据库平台之一。 以下是对MySQL数据库的详细介绍: 核心特性与优势 ...

      一个基于spring boot、druid、mybatis、mysql的后端基础.zip

      自1998年首次发布以来,MySQL以其卓越的性能、可靠性和可扩展性,成为全球范围内Web应用程序、企业级解决方案以及其他各种数据处理场景的首选数据库平台之一。 以下是对MySQL数据库的详细介绍: 核心特性与优势 ...

    Global site tag (gtag.js) - Google Analytics