mybatis开启spring事务代码解析

2025-05-29 0 83

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>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

<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、总结

以上就是利用mybatisspring完成了对事务操作的简要案例。可以对数据库事务隔离级别进行配置,mysql的数据库隔离级别是connection维度的。

还可以设置事务的超时时间,即超时事务自动回滚。

以上就是本文关于mybatis开启spring事务代码解析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

原文链接:http://blog.csdn.net/itbuluoge/article/details/71517284

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 mybatis开启spring事务代码解析 https://www.kuaiidc.com/113786.html

相关文章

发表评论
暂无评论