mybatis開啟spring事務代碼解析
1、事務
Spring事務的本質(zhì)其實就是數(shù)據(jù)庫對事務的支持,沒有數(shù)據(jù)庫的事務支持,spring是無法提供事務功能的。最終都是調(diào)用數(shù)據(jù)庫連接來完成事務的開啟、提交和回滾。
2、模塊
那么在對于spring事務而言,幾個不可或缺的模塊就是數(shù)據(jù)源、事務管理器以及事務編程
3、xml配置
<!--事務管理器--> <bean id="springTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!--數(shù)據(jù)源--> <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、事務編程
@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完成了對事務操作的簡要案例??梢詫?shù)據(jù)庫事務隔離級別進行配置,mysql的數(shù)據(jù)庫隔離級別是connection維度的。
還可以設置事務的超時時間,即超時事務自動回滾。
以上就是本文關于mybatis開啟spring事務代碼解析的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關文章
SpringBoot與spring security的結合的示例
這篇文章主要介紹了SpringBoot與spring security的結合的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03