作者:郭无心
链接:https://www.zhihu.com/question/30206875/answer/84675373
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

http://czj4451.iteye.com/blog/2037759

mybatis的事务管理:
一、单独使用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(); // 关闭会话,释放资源
}
}
}

测试会发现数据没有被修改

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

 <!-- 数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" lazy-init="true">
<property name="driverClassName">
<value>org.logicalcobwebs.proxool.ProxoolDriver</value>
</property>
<property name="url">
<value>proxool.gcld</value>
</property>
</bean> <!-- sessionFactory -->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml">
</property>
<property name="dataSource" ref="dataSource"/>
</bean> <!-- 事务管理器 -->
<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();
}
}
================================================================================
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="yourDataSource" />
</bean>
@Transactional
public void blabla(){
}

spring整合mybatis是如何配置事务的?的更多相关文章

  1. spring整合mybatis二种配置

    第一种: <!-- 配置sqlsession --> <bean id="sqlsessionFactory" class="org.mybatis.s ...

  2. spring整合mybatis,ioc容器及声明式事务配置

    步骤: 1.创建jdbc.properties文件,用来管理存放连接数据库的相关信息 jdbc.properties:jdbc.user=root jdbc.password=123456 jdbc. ...

  3. spring整合mybatis(hibernate)配置

    一.Spring整合配置Mybatis spring整合mybatis可以不需要mybatis-config.xml配置文件,直接通过spring配置文件一步到位.一般需要具备如下几个基本配置. 1. ...

  4. spring基础:什么是框架,框架优势,spring优势,耦合内聚,什么是Ioc,IOC配置,set注入,第三方资源配置,综合案例spring整合mybatis实现

    知识点梳理 课堂讲义 1)Spring简介 1.1)什么是框架 源自于建筑学,隶属土木工程,后发展到软件工程领域 软件工程中框架的特点: 经过验证 具有一定功能 半成品 1.2)框架的优势 提高开发效 ...

  5. spring 整合 mybatis 中数据源的几种配置方式

    因为spring 整合mybatis的过程中, 有好几种整合方式,尤其是数据源那块,经常看到不一样的配置方式,总感觉有点乱,所以今天有空总结下. 一.采用org.mybatis.spring.mapp ...

  6. Spring学习总结(六)——Spring整合MyBatis完整示例

    为了梳理前面学习的内容<Spring整合MyBatis(Maven+MySQL)一>与<Spring整合MyBatis(Maven+MySQL)二>,做一个完整的示例完成一个简 ...

  7. Spring学习总结(五)——Spring整合MyBatis(Maven+MySQL)二

    接着上一篇博客<Spring整合MyBatis(Maven+MySQL)一>继续. Spring的开放性和扩张性在J2EE应用领域得到了充分的证明,与其他优秀框架无缝的集成是Spring最 ...

  8. Spring学习总结(五)——Spring整合MyBatis(Maven+MySQL)一

    MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中. 使用这个类库中的类, Spring 将会加载必要的MyBatis工厂类和 session 类. 这个类库 ...

  9. Spring整合MyBatis(一)MyBatis独立使用

    摘要: 本文结合<Spring源码深度解析>来分析Spring 5.0.6版本的源代码.若有描述错误之处,欢迎指正. MyBatis本是Apache的一个开源项目iBatis,2010年这 ...

随机推荐

  1. windows安装React Native开发运行环境

    React Native是什么 React Native是facebook开源的一个用于开发app的框架.React Native的设计理念:既拥有Native (原生) 的用户体验.又保留React ...

  2. ubuntu上安装MySQL详解

     1. 安装 在终端输入 sudo apt-get install mysql-server mysql-client 回车 2.安装完成后检测MySQL的状态 systemctl status my ...

  3. linux -j 4

    把源码编译成可执行的二进制文件, 4为服务器内核数

  4. Oracle数据库,基础知识

    1.Oracle的五大约束条件: 1 主键  primary key2 外键  foreign key,3 唯一  unique,4 检测  check5 非空  not null 实例运用: -- ...

  5. 【Mac 10.13.0】安装 libimobiledevice,提示报错:warning: unable to access '/Users/lucky/.config/git/attributes': Permission denied解决方案

    打开终端,执行命令: 1.sudo chown -R XXX /usr/local  (XXX表示当前用户名) 2.ruby -e "$(curl -fsSL https://raw.git ...

  6. 得分(UVa1585)

    题目具体描述见:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_prob ...

  7. HTK训练错误消息意义

    在HTK训练线上数据的时候,遇到了ERROR [+6550] LoadHTKLabels: Junk at end of HTK transcription,这个问题,网上查阅是说有空行,结果根本没有 ...

  8. easyui layout 左右面板折叠后 显示标题

    (function($){ var buttonDir = {north:'down',south:'up',east:'left',west:'right'};    $.extend($.fn.l ...

  9. Java 中如何计算两个字符串时间之间的时间差?(单位为分钟)

    Java 中如何计算两个字符串时间之间的时间差?(单位为分钟) import java.text.DateFormat; import java.text.ParseException; import ...

  10. 初探Java字符串

    转载: 初探Java字符串 String印象 String是java中的无处不在的类,使用也很简单.初学java,就已经有字符串是不可变的盖棺定论,解释通常是:它是final的. 不过,String是 ...