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完成了對事務操作的簡要案例??梢詫祿焓聞崭綦x級別進行配置,mysql的數據庫隔離級別是connection維度的。
還可以設置事務的超時時間,即超時事務自動回滾。
以上就是本文關于mybatis開啟spring事務代碼解析的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/itbuluoge/article/details/71517284