1、事务
Spring事务的本质其实就是数据库对事务的支持,没有数据库的事务支持,spring是无法提供事务功能的。最终都是调用数据库连接来完成事务的开启、提交和回滚。
2、模块
那么在对于spring事务而言,几个不可或缺的模块就是数据源、事务管理器以及事务编程
3、xml配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<!--事务管理器-->
< bean id = "springTransactionManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager" >
< property name = "dataSource" ref = "dataSource" />
</ bean >
<!--数据源-->
< bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource" >
< property name = "driverClassName" value = "com.mysql.jdbc.Driver" />
< property name = "url" value = "jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8" />
< property name = "username" value = "root" />
< property name = "password" value = "123456" />
</ bean >
< property name = "dataSource" ref = "dataSource" />
<!-- 指定sqlMapConfig总配置文件,订制的environment在spring容器中不在生效-->
<!--指定实体类映射文件,可以指定同时指定某一包以及子包下面的所有配置文件,mapperLocations和configLocation有一个即可,当需要为实体类指定别名时,可指定configLocation属性,再在mybatis总配置文件中采用mapper引入实体类映射文件 -->
<!--<property name="configLocation" value="classpath:fwportal/beans/dbconfig/mybatis.xml" />-->
< property name = "mapperLocations" value = "classpath:mapper/*.xml" />
</ bean >
<!--将DAO接口注册为BEAN-->
< bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer" >
< property name = "basePackage" value = "TRANSACTION.DAO" />
</ bean >
|
4、事务编程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
@Test
public void testDelete() throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext( "mysqltransaction.xml" );
DataSourceTransactionManager springTransactionManager = (DataSourceTransactionManager) context.getBean( "springTransactionManager" );
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
//开启事务
TransactionStatus status = springTransactionManager.getTransaction(def);
final StudentDAO dao = (StudentDAO)context.getBean( "studentDAO" );
try {
dao.delete(2L);
}
catch (Exception ex) {
springTransactionManager.rollback(status);
//事务回滚
throw ex;
}
springTransactionManager.commit(status);
//事务提交
}
|
5、总结
以上就是利用mybatis和spring完成了对事务操作的简要案例。可以对数据库事务隔离级别进行配置,mysql的数据库隔离级别是connection维度的。
还可以设置事务的超时时间,即超时事务自动回滚。
以上就是本文关于mybatis开启spring事务代码解析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
原文链接:http://blog.csdn.net/itbuluoge/article/details/71517284