您的位置:首页 > 编程语言 > Java开发

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

2016-07-03 16:16 447 查看

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的账号的话,我们可以互粉哦!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: