1. Spring事务处理

使用MyBatis,你可以写代码去控制事务操作。例如,提交事务和回滚事务。

public Student createStudent(Student student)
{
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().
openSession();
try {
StudentMapper mapper =
sqlSession.getMapper(StudentMapper.class);
mapper.insertAddress(student.getAddress());
mapper.insertStudent(student);
sqlSession.commit();
return student;
}
catch (Exception e) {
sqlSession.rollback();
throw new RuntimeException(e);
}
finally {
sqlSession.close();
}
}

上面的方法中,我们可能会在每一个方法中,都需要添加事务的提交、回滚、关闭等。为了使用Spring的事务处理能力,我们需要配置TransactionManager在Spring的配置文件中。

<bean id="transactionManager" class="org.springframework.jdbc.
datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>

这个dataSource涉及到的需要事务处理的相同的dataSource,这个将会用到SqlSessionFactory的bean中。

基于注解的事务处理特性,Spring需要先使用下面的配置:

<tx:annotation-driven transaction-manager="transactionManager"/>

现在你可以在Spring的服务的Bean中注解@ Transactional。这个注解表明每个方法都是Spring来管理的。如果方法成功处理,那么Spring就会提交事务;如果就去处理过程出现了错误,那么事务就会被回滚。当然,Spring将会关心MyBatis的转换过程是否出现Exceptons的DataAccessExceptions的异常栈。

@Service
@Transactional
public class StudentService
{
@Autowired
private StudentMapper studentMapper;
public Student createStudent(Student student)
{
studentMapper.insertAddress(student.getAddress());
if(student.getName().equalsIgnoreCase("")){
throw new RuntimeException("Student name should not be
empty.");
}
studentMapper.insertStudent(student);
return student;
}
}

下面是配置applicationContext.xml的文件:

<beans>
<context:annotation-config />
<context:component-scan base-package="com.owen.mybatis" />
<context:property-placeholder
location="classpath:application.properties" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.
DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.owen.mybatis.mappers" />
</bean>
<bean id="sqlSession"
class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliases"
value="com.owen.mybatis.domain.Student,
com.owen.mybatis.domain.Tutor"/>
<property name="typeAliasesPackage"
value="com.owen.mybatis.domain"/>
<property name="typeHandlers"
value="com.owen.mybatis.typehandlers.PhoneTypeHandler"/>
<property name="typeHandlersPackage"
value="com.owen.mybatis.typehandlers"/>
<property name="mapperLocations"
value="classpath*:com/mybatis3/**/*.xml" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.
DriverManagerDataSource">
<property name="driverClassName"
value="${jdbc.driverClassName}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
</beans>

下面写个测试类来测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml"
)
public class StudentServiceTest
{
@Autowired
private StudentService studentService;
@Test
public void testCreateStudent() {
Address address = new Address(0,"Quaker Ridge
Rd.","Bethel","Brooklyn","06801","USA");
Student stud = new Student();
long ts = System.currentTimeMillis();
stud.setName("stud_"+ts);
stud.setEmail("stud_"+ts+"@gmail.com");
stud.setAddress(address);
Student student = studentService.createStudent(stud);
assertNotNull(student);
assertEquals("stud_"+ts, student.getName());
assertEquals("stud_"+ts+"@gmail.com", student.getEmail());
System.err.println("CreatedStudent: "+student);
}
@Test(expected=DataAccessException.class)
public void testCreateStudentForException() {
Address address = new Address(0,"Quaker Ridge
Rd.","Bethel","Brooklyn","06801","USA");
Student stud = new Student();
long ts = System.currentTimeMillis();
stud.setName("Timothy");
stud.setEmail("stud_"+ts+"@gmail.com");
stud.setAddress(address);
studentService.createStudent(stud);
fail("You should not reach here");
}
}

2. 总结

通过这几个章节的学习,笔者向大家介绍了MyBatis如何与Spring进行整合,及如何运用Spring来管理事务。到目前为止,笔者已经向大家介绍的MyBatis的知识也就这些了,如何你想了解更多关于MyBatis的知识,可以去查看其它的文档。最后,笔者真诚感谢读取对本博客的关注,这也是笔者第一次翻译一本书,翻译不好的地方请谅解,笔者会继续努力学好英语,希望可以带给大家更多好的作品。谢谢您们的支持!如果需要源码的话,请登录:https://github.com/owenwilliam/mybatis.com.git。 如果你有GitHub的账号的话,我们可以互粉哦!

MyBatis集合Spring(四)之使用Spring处理事务相关推荐

  1. Spring(四)——AOP、Spring实现AOP、Spring整合Mybatis、Spring中的事务管理

    文章目录 1. 什么是AOP 2. 使用Spring实现AOP 2.1 使用Spring的API 接口实现 2.2 自定义实现 2.3 使用注解实现 3. 整合MyBatis 3.1 MyBatis- ...

  2. mybatis学习(四)连接池、事务、动态SQL、多表查询

    目录 连接池 事务 动态SQL 1.if标签 2.where标签 3.foreach标签 4.sql标签 多表操作 (一)一对多.多对一 .一对一 1.查询所有账户,在账户信息后显示所属的用户的用户名 ...

  3. 源码通透-mybatis源码分析以及整合spring过程

    源码通透-mybatis源码分析以及整合spring过程 mybatis源码分析版本:mybaits3 (3.5.0-SNAPSHOT) mybatis源码下载地址:https://github.co ...

  4. docker 打包镜像_Spring Boot2 系列教程(四十一)部署 Spring Boot 到远程 Docker 容器

    不知道各位小伙伴在生产环境都是怎么部署 Spring Boot 的,打成 jar 直接一键运行?打成 war 扔到 Tomcat 容器中运行?不过据松哥了解,容器化部署应该是目前的主流方案. 不同于传 ...

  5. spring boot+Mybatis+mysql+atomikos+jta实现多数据源分布式事务

    spring boot+Mybatis+mysql+atomikos+jta实现多数据源分布式事务 1.导入相关依赖 2.配置相关application.properties 3.创建配置文件 4.创 ...

  6. Spring Security技术栈学习笔记(十四)使用Spring Social集成QQ登录验证方式

    上一篇文章<Spring Security技术栈开发企业级认证与授权(十三)Spring Social集成第三方登录验证开发流程介绍>主要是介绍了OAuth2协议的基本内容以及Spring ...

  7. Spring入门(包括spring整合mybatis的spring-mybatis)

    Spring 一.背景介绍 1.spring理念 使现有的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架 Spring是一个轻量级控制反转(lOC)和面向切面(AOP)的容器框架 2.轮子理 ...

  8. Spring学习笔记:Spring整合Mybatis(mybatis-spring.jar)(二:mybatis整合spring)

    http://blog.csdn.net/qq598535550/article/details/51703190 二.Spring整合mybatis其实是在mybatis的基础上实现Spring框架 ...

  9. Spring Boot2.x-10 基于Spring Boot 2.1.2 + Mybatis 2.0.0实现多数据源,支持事务

    文章目录 概述 思路 步骤 Step1 多数据源配置文件applicaiton.yml Step2 初始化多个数据源 Step3 配置多个数据源 验证测试 支持事务 Step1 配置类中通过@Bean ...

  10. Spring Boot2.x-09 基于Spring Boot 2.1.2 + Mybatis使用自定义注解实现数据库切换

    文章目录 概述 场景说明:读写分离 操作步骤 工程结构 Step1 自定义注解 Step2 数据源定义 Step3 配置文件配置数据源 Step4 数据源实例化DatasourceConfig Ste ...

最新文章

  1. 新手UI设计师必需要掌握的知识和技能
  2. bootstrap34-带有导航栏的字体图标
  3. 为什么我的elec352稍微有点崩
  4. Python自动化运维工具-Fabric部署及使用总结
  5. Debian update apache error AH00111: Config vairable ${APACHE_RUN_DIR} is not defined
  6. C++ 模板(template) 的定义
  7. java中wait的场景,wait——webdriver实用指南java版
  8. File Hunter for mac - 丢失文件查找AE脚本
  9. 清华大学开源迁移学习算法库:基于PyTorch实现已有算法
  10. java 容器 List
  11. 离散数学蕴含等值式前件为假时命题为真的理解
  12. Android调用默认浏览器打开指定url
  13. 计算机应用基础三次没有通过怎么办,计算机应用基础第三次作业
  14. 所有ghost操作系统大全
  15. 利用VGA输出音频信号
  16. 全手动封装教程+SRS9.80102 文本教程(适合初学)
  17. 速达服务器应用程序错误,速达软件错误集锦及解决方法
  18. wireshark 报文分析心得 -- Identification 使用说明
  19. Nice UI - Hacked.io
  20. Ceilometer原理及介绍

热门文章

  1. 【20171227】json
  2. java两个数的最大公约数和最小公倍数
  3. 【转】hadoop2.6 配置lzo压缩
  4. 树形DP+二分(Information Disturbing HDU3586)
  5. Java2十大经典中文图书
  6. 如何实现一个简单的熔断以及Hystrix原理分析
  7. 英特尔一口气发布了三款处理器、两款存储、一款以太网适配器
  8. bitnami下mysql配置-包含phpMyAdmin配置
  9. sitemesh 2.4 装饰器学习
  10. 用 Graphviz+pvtrace 可视化函数调用