设为首页 收藏本站
查看: 823|回复: 0

[经验分享] myBatis系列之七:事务管理

[复制链接]

尚未签到

发表于 2016-11-26 07:40:56 | 显示全部楼层 |阅读模式
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、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-305613-1-1.html 上篇帖子: Mybatis使用经验分享之批量操作 下篇帖子: 14、mybatis与spring、springmvc集成
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表