javascript
MyBatis及Spring事务初学总结
MyBatis是從iBatis項(xiàng)目繼承而來,是目前互聯(lián)網(wǎng)公司的主流數(shù)據(jù)訪問層框架。
在實(shí)際使用中與Spring一起使用。MyBatis出了MyBatis-Spring組件,用于兩者之間的整合,使用Spring的事務(wù)管理功能。
92 <dependency>93 <groupId>org.mybatis</groupId>94 <artifactId>mybatis-spring</artifactId>95 <version>1.2.2</version>96 </dependency>DataSourceTransactionManager是Spring框架的組件,通過java.sql.connection來管理事務(wù)(通過commit()提交事務(wù),或者通過rollback()回滾事務(wù))
使用MyBatis的事務(wù)有兩種方式:1.注解驅(qū)動(dòng);2.XML驅(qū)動(dòng)
38 <!-- (事務(wù)管理)transaction manager, use JtaTransactionManager for global tx -->39 <bean id="transactionManager"40 class="org.springframework.jdbc.datasource.DataSourceTransactionManager">41 <property name="dataSource" ref="dataSource" />42 </bean>43 44 <tx:advice id="userTxAdvice" transaction-manager="transactionManager">45 <tx:attributes>46 <tx:method name="delete*" propagation="REQUIRED" read-only="false"47 rollback-for="java.lang.Exception" no-rollback-for="java.lang.RuntimeException" />48 <tx:method name="insert*" propagation="REQUIRED" read-only="false"49 rollback-for="java.lang.Exception" />50 <tx:method name="update*" propagation="REQUIRED" read-only="false"51 no-rollback-for="java.lang.RuntimeException" rollback-for="java.lang.Exception"/>52 <tx:method name="find*" propagation="SUPPORTS" />53 <tx:method name="get*" propagation="SUPPORTS" />54 <tx:method name="select*" propagation="SUPPORTS" />55 <tx:method name="*Transaction*" no-rollback-for="java.lang.RuntimeException" rollback-for="java.lang.Exception"/>56 </tx:attributes>57 </tx:advice>58 59 <aop:config>60 <aop:pointcut id="pc"61 expression="execution(public * com.service.impl.*.*(..))" /> <!--把事務(wù)控制在Service層 -->62 <aop:advisor pointcut-ref="pc" advice-ref="userTxAdvice" />63 </aop:config>64 65 66 <!-- 創(chuàng)建SqlSessionFactory,同時(shí)指定數(shù)據(jù)源 -->67 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">68 <property name="configLocation" value="/WEB-INF/mybatis-config.xml"></property>69 <property name="dataSource" ref="dataSource" />70 </bean>dataSource是通過dataSource.properties來進(jìn)行配置的(這里有疑問,這樣實(shí)現(xiàn)的話,spring的事務(wù)框架連接數(shù)據(jù)庫時(shí)使用的就是com.mysql.jdbc.Driver,就沒有連接池管理功能了吧?)
一般如下配置
driver=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/myfirstbase username=XXXX password=XXXX而mybatis-config.xml中一般配置的是
1 <?xml version="1.0" encoding="UTF-8"?>2 <!DOCTYPE configuration3 PUBLIC "-//mybatis.org//DTDConfig 3.0//EN"4 "http://mybatis.org/dtd/mybatis-3-config.dtd">5 6 <!-- mybatis的數(shù)據(jù)類型和處理器等等...都可以實(shí)現(xiàn)接口重寫,然后配置 -->7 <configuration>8 9 <typeAliases>10 <package name="com.model" />11 </typeAliases>12 13 <mappers>14 <!--映射文件-->15 <mapper resource="com/mapper/userMapper.xml"/>16 </mappers>17 </configuration>而userMapper.xml一般如下,同時(shí)需要一個(gè)interface,定義這些方法。
<?xml version="1.0" encoding="UTF-8"?>2 <!DOCTYPE mapper3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">5 6 7 <mapper namespace="com.mapper.IUserMapper">8 9 <select id="selectAllUser" resultMap="UserMapper">10 select * from TEST_LEE11 </select>12 13 <resultMap type="User" id="UserMapper" autoMapping="true">14 <id property="id" column="id"/>15 <result property="name" column="name"/>16 <result property="user_id" column="user_id"/>17 </resultMap>18 19 <select id="selectById" parameterType="int" resultType="User">20 select * from TEST_LEE where id=#{id}21 </select>22 23 24 <insert id="insertUser" parameterType="User">25 insert into TEST_LEE (user_id, name) values(#{user_id},#{name})26 </insert>27 28 <update id="updateUser" parameterType="User">29 update TEST_LEE set name=#{name}, user_id=#{user_id} where id=#{id}30 </update>31 32 <delete id="deleteUser" parameterType="int">33 delete from TEST_LEE where id=#{id}34 </delete>35 36 <!-- 返回自增ID會(huì)賦值到User.id -->37 <insert id="insertResultGeneratedKey" parameterType="User" useGeneratedKeys="true" keyProperty="id">38 insert into TEST_LEE (user_id, name) values(#{user_id},#{name})39 </insert>40 41 </mapper>?
這其中的sqlSessionFactory是用Spring的SqlSessionFactoryBean來配置創(chuàng)建的,但是一般不直接使用,而是將其注入到了org.mybatis.spring.mapper.MapperFactoryBean中,或者其他擴(kuò)展了SqlSessionDaoSupport的DAO中。
?
109 <!-- Mapper接口所在包名,Spring會(huì)自動(dòng)查找其下的Mapper --> 110 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 111 <property name="basePackage" value="com.mapper" /> 112 </bean> 113 114 <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 115 <property name="mapperInterface" value="com.mapper.IUserMapper" /> 116 <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> 117 </bean>SqlSessionTemplate是MyBatis-Spring的核心類,負(fù)責(zé)管理MyBatis的SqlSession,調(diào)用MyBatis的SQL方法,翻譯異常等,但是
為了代替手動(dòng)使用SqlSessionDaoSupport或SqlSessionTemplate,MyBatis-Spring提供了一個(gè)動(dòng)態(tài)代理的實(shí)現(xiàn),即MapperFactoryBean,從而直接注入數(shù)據(jù)映射器到Service層bean中,MapperFactoryBean負(fù)責(zé)處理SqlSession的創(chuàng)建和關(guān)閉,使用了Spring事務(wù)后,事務(wù)完成時(shí),session將會(huì)提交或者回滾。
?
?
2.Spring的事務(wù)的傳播行為和隔離級(jí)別
提及Spring中的聲明式事務(wù),通常提及特性包括:事務(wù)的傳播行為、隔離級(jí)別、只讀、事務(wù)超時(shí)、回滾規(guī)則,可以參見上面的規(guī)則定義。
其中事務(wù)的傳播行為有7種,比較常見的是REQUIRED、SUPPORTS、REQUIRES_NEW、NESTED??蓞⒖歼@里的圖示http://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html#tx-propagation
具體列出如下
PROPAGATION_MANDATORY ?強(qiáng)制的,表示該方法必須運(yùn)行在一個(gè)事務(wù)中,否則拋出異常
PROPAGATION_NESTED ? ? 嵌套的,若當(dāng)前已經(jīng)有一個(gè)事務(wù),則這個(gè)方法在其中在運(yùn)行于一個(gè)嵌套其中的事務(wù),可獨(dú)立的提交或回滾
PROPAGATION_NEVER ? ? 不應(yīng)該運(yùn)行在事務(wù)中,如果一個(gè)事務(wù)正在運(yùn)行則拋出異常
PROPAGATION_NOT_SUPPORTED ? 不應(yīng)該運(yùn)行在事務(wù)中,如果一個(gè)事務(wù)正在運(yùn)行,則將該事務(wù)掛起
PROPAGATION_SUPPORTS ? ?不需要事務(wù)上下文,但是也支持,如果有一個(gè)事務(wù)已經(jīng)在運(yùn)行,則該方法也可以在事務(wù)中運(yùn)行
PROPAGATION_REQUIRES_NEW ? 需要新的事務(wù)。表示需要一個(gè)新的事務(wù),如果一個(gè)現(xiàn)有事務(wù)正在運(yùn)行,則該現(xiàn)有事務(wù)將被掛起
PROPAGATION_REQUIRED ?需要事務(wù),如果現(xiàn)在一個(gè)現(xiàn)有事務(wù)正在運(yùn)行,則該方法直接在該事務(wù)中運(yùn)行,否則起個(gè)新的事務(wù)
PROPAGATION_NESTED can only be used with a DataSourceTransactionManager and a JDBC3 driver. It uses save points in order to be able to rollback some part of a transaction (i.e. what constitutes the nested transaction in Spring terms). See the javadoc of Connection to see how save points work.事務(wù)的隔離級(jí)別5種,用于說明受其他并發(fā)的事務(wù)的影響程度,通過鎖表完全隔離當(dāng)然可以做到?jīng)]有影響,但這種情況下性能損失太大,并不適用所有場景。
ISOLATION_DEFAULT ? 默認(rèn)的,適用數(shù)據(jù)庫后端設(shè)置
ISOLATION_READ_UNCOMMITTED ??允許讀取尚未提交的更改??赡軐?dǎo)致Dirty read、Phantom reads或Nonrepeatable read。
ISOLATION_READ_COMMITTED ? 允許從已經(jīng)提交的并發(fā)事務(wù)讀取,不會(huì)出現(xiàn)Dirty read,但是會(huì)出現(xiàn)Phantom reads或Nonrepeatable read。
ISOLATION_REPEATABLE_READ ? 對(duì)相同字段的多次讀取需一直。不會(huì)出現(xiàn)Dirty read或Nonrepeatable read,但是還是可能出現(xiàn)Phantom read。
ISOLATION_SERIALIZABLE ?完全服從ACID(原子性、一致性、隔離性、持久性)原則,確保不會(huì)出現(xiàn)Dirty read、Nonrepeatable read或Phantom read。
事務(wù)超時(shí)
事務(wù)只讀
事務(wù)回滾規(guī)則:默認(rèn)情況下只對(duì)繼承自RuntimeException的異常(Unckecked Exception)進(jìn)行回滾。
3.MyBatis涉及到分庫分表怎么辦
分庫分表要解決的問題是因數(shù)據(jù)庫存儲(chǔ)量大了和訪問量大了進(jìn)行的水平擴(kuò)展問題
這里可以參考這幾個(gè)鏈接,
https://github.com/makersoft/mybatis-shards
其中CobarClient是阿里的解決方案
ShardBatis:http://code.google.com/p/shardbatis/
參考資料:
1.《Spring in action》
2.https://mybatis.github.io/mybatis-3/index.html
3.https://guptavikas.wordpress.com/2010/04/15/aspectj-pointcut-expressions/
4.https://www.ibm.com/developerworks/cn/education/opensource/os-cn-spring-trans/
5.http://m.oschina.net/blog/120707
6.http://gemantic.iteye.com/blog/1622799
7.http://www.douban.com/note/227015659/
?
轉(zhuǎn)載于:https://www.cnblogs.com/majia1949/p/4626652.html
總結(jié)
以上是生活随笔為你收集整理的MyBatis及Spring事务初学总结的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 导航栏对于UIScrollview以及子
- 下一篇: (转)Spring定时任务的几种实现