原文地址:http://czj4451.iteye.com/blog/2037759
mybatis与spring结合后,事务管理更加方便,这里介绍使用transactionnal的方式,有错的的地方,希望大家指出。
1. 和Spring集成后,使用Spring的事务管理:
a. @Transactional方式:
在类路径下创建beans-da-tx.xml文件,在beans-da.xml(系列五)的基础上加入事务配置:
-
<!-- 配置事务管理器,注意这里的dataSource和SqlSessionFactoryBean的dataSource要一致,不然事务就没有作用了 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
-
<tx:annotation-driven transaction-manager="transactionManager" /><!-- 事务注解驱动,标注@Transactional的类和方法将具有事务性 -->
服务类:
- @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;
- }
- }
mybatic与spring结合的事务管理
原文:http://www.cnblogs.com/dylenwu/p/6128537.html