MyBatis集合Spring(四)之使用Spring处理事务

来源:互联网 发布:c语言嵌入式汇编 编辑:程序博客网 时间:2024/05/29 02:25

1. Spring事务处理

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

[java] view plain copy
  1. public Student createStudent(Student student)  
  2. {  
  3. SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().  
  4. openSession();  
  5. try {  
  6. StudentMapper mapper =  
  7. sqlSession.getMapper(StudentMapper.class);  
  8. mapper.insertAddress(student.getAddress());  
  9. mapper.insertStudent(student);  
  10. sqlSession.commit();  
  11. return student;  
  12. }  
  13. catch (Exception e) {  
  14. sqlSession.rollback();  
  15. throw new RuntimeException(e);  
  16. }  
  17. finally {  
  18. sqlSession.close();  
  19. }  
  20. }  

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

[html] view plain copy
  1. <bean id="transactionManager" class="org.springframework.jdbc.  
  2. datasource.DataSourceTransactionManager">  
  3. <property name="dataSource" ref="dataSource" />  
  4. </bean>  

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

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

[html] view plain copy
  1. <tx:annotation-driven transaction-manager="transactionManager"/>  

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

[java] view plain copy
  1. @Service  
  2. @Transactional  
  3. public class StudentService  
  4. {  
  5. @Autowired  
  6. private StudentMapper studentMapper;  
  7. public Student createStudent(Student student)  
  8. {  
  9. studentMapper.insertAddress(student.getAddress());  
  10. if(student.getName().equalsIgnoreCase("")){  
  11. throw new RuntimeException("Student name should not be  
  12. empty.");  
  13. }  
  14. studentMapper.insertStudent(student);  
  15. return student;  
  16. }  
  17. }  

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

[html] view plain copy
  1. <beans>  
  2. <context:annotation-config />  
  3. <context:component-scan base-package="com.owen.mybatis" />  
  4. <context:property-placeholder  
  5. location="classpath:application.properties" />  
  6. <tx:annotation-driven transaction-manager="transactionManager"/>  
  7. <bean id="transactionManager"  
  8. class="org.springframework.jdbc.datasource.  
  9. DataSourceTransactionManager">  
  10. <property name="dataSource" ref="dataSource" />  
  11. </bean>  
  12. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  13. <property name="basePackage" value="com.owen.mybatis.mappers" />  
  14. </bean>  
  15. <bean id="sqlSession"  
  16. class="org.mybatis.spring.SqlSessionTemplate">  
  17. <constructor-arg index="0" ref="sqlSessionFactory" />  
  18. </bean>  
  19. <bean id="sqlSessionFactory"  
  20. class="org.mybatis.spring.SqlSessionFactoryBean">  
  21. <property name="dataSource" ref="dataSource" />  
  22. <property name="typeAliases"  
  23. value="com.owen.mybatis.domain.Student,  
  24. com.owen.mybatis.domain.Tutor"/>  
  25. <property name="typeAliasesPackage"  
  26. value="com.owen.mybatis.domain"/>  
  27. <property name="typeHandlers"  
  28. value="com.owen.mybatis.typehandlers.PhoneTypeHandler"/>  
  29. <property name="typeHandlersPackage"  
  30. value="com.owen.mybatis.typehandlers"/>  
  31. <property name="mapperLocations"  
  32. value="classpath*:com/mybatis3/**/*.xml" />  
  33. </bean>  
  34. <bean id="dataSource"  
  35. class="org.springframework.jdbc.datasource.  
  36. DriverManagerDataSource">  
  37. <property name="driverClassName"  
  38. value="${jdbc.driverClassName}"></property>  
  39. <property name="url" value="${jdbc.url}"></property>  
  40. <property name="username" value="${jdbc.username}"></property>  
  41. <property name="password" value="${jdbc.password}"></property>  
  42. </bean>  
  43. </beans>  

下面写个测试类来测试:

[java] view plain copy
  1. @RunWith(SpringJUnit4ClassRunner.class)  
  2. @ContextConfiguration(locations="classpath:applicationContext.xml"  
  3. )  
  4. public class StudentServiceTest  
  5. {  
  6. @Autowired  
  7. private StudentService studentService;  
  8. @Test  
  9. public void testCreateStudent() {  
  10. Address address = new Address(0,"Quaker Ridge  
  11. Rd.","Bethel","Brooklyn","06801","USA");  
  12. Student stud = new Student();  
  13. long ts = System.currentTimeMillis();  
  14. stud.setName("stud_"+ts);  
  15. stud.setEmail("stud_"+ts+"@gmail.com");  
  16. stud.setAddress(address);  
  17. Student student = studentService.createStudent(stud);  
  18. assertNotNull(student);  
  19. assertEquals("stud_"+ts, student.getName());  
  20. assertEquals("stud_"+ts+"@gmail.com", student.getEmail());  
  21. System.err.println("CreatedStudent: "+student);  
  22. }  
  23. @Test(expected=DataAccessException.class)  
  24. public void testCreateStudentForException() {  
  25. Address address = new Address(0,"Quaker Ridge  
  26. Rd.","Bethel","Brooklyn","06801","USA");  
  27. Student stud = new Student();  
  28. long ts = System.currentTimeMillis();  
  29. stud.setName("Timothy");  
  30. stud.setEmail("stud_"+ts+"@gmail.com");  
  31. stud.setAddress(address);  
  32. studentService.createStudent(stud);  
  33. fail("You should not reach here");  
  34. }  
  35. }  

2. 总结

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