事務處理(一) - spring事務
- 2019 年 10 月 30 日
- 筆記
Spring的事務管理
原理
Spring是通過org.springframework.transaction.PlatformTransactionManager介面來實現事務的管理。同時應對不同的場景,提供不同的PlatformTransactionManager實現類來實現管理事務。下面是常見的應用場景。
JDBC事務
如果使用JDBC來進行數據持久化,Spring使用DataSourceTransactionManager類來實現事務管理(mybatis也可以使用JDBC的事務管理,mybatis的事務機制在下延伸中講解)。Spring配置如下
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean>
Hibernate事務
如果使用Hibernate來進行數據持久化,Spring使用HibernateTransactionManager類來實現事務管理。Spring配置如下
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean>
延伸:mybatis的事務機制
MyBatis的事務管理分為兩種形式:
- 使用JDBC的事務管理機制:即利用java.sql.Connection對象完成對事務的提交(commit())、回滾(rollback())、關閉(close())等
- 使用MANAGED的事務管理機制:這種機制MyBatis自身不會去實現事務管理,而是讓程式的容器如(JBOSS,Weblogic)來實現對事務的管理
Spring事務的隔離級別
Spring除了jdbc的四種事務讀未提交ISOLATION_READ_UNCOMMITTED、讀已提交ISOLATION_READ_COMMITTED、可重複讀ISOLATION_REPEATABLE_READ、串列化ISOLATION_SERIALIZABLE以外,還有ISOLATION_DEFAULT,即使用資料庫默認事務隔離級別。
Spring事務的隔離級別配置
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:annotation-driven order="1" proxy-target-class="true"/> <tx:advice id="transactionAdvice"> <tx:attributes> <tx:method name="*" isolation="READ_COMMITTED" rollback-for="Exception"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* com.lc.service..*Service.*(..))"/> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" order="2"/> </aop:config>
Spring事務的傳播行為
7種傳播行為介紹
Spring的事務傳播行為有一下7種
- REQUIRED:支援當前事務,如果當前沒有事務就新創建一個事務
- REQUIRES_NEW: 新建事務,如果當前存在事務,就把當前事務掛起。
- NOT_SUPPORTED: 在非事務環境下執行,如果當前存在事務,就把當前事務掛起
- SUPPORTS: 支援當前事務,如果當前沒有事務,就在非事務環境下執行
- MANDATORY: 支援當前事務,如果當前沒有事務,就拋出異常。
- NEVER: 在非事務環境下執行,如果當前存在事務就拋出異常。
- NESTED: 如果當前存在事務,則在嵌套事務內執行;如果當前沒有事務,則進行與REQUIRED類似的操作;擁有多個可以回滾的保存點,內部回滾不會對外部事務產生影響。它只對DataSourceTransactionManager事務管理器起效。
事務傳播行為的理解,事務是可以嵌套的,如一個方法存在事務,它調用一個方法也存在事務,如果調用的方法的事務是REQUIRED時,調用的方法不會新建事務,而是使用老的事務;如果調用方法的事務是REQUIRESNEW時,調用的方法會新建事務,而之前的事務會掛起,等這個方法結束再調用,不過這會導致事務不同步,即內部方法成功了,沒有回滾,外部方法失敗回滾了。
使用方式
@Transactional(readOnly = true, propagation=Propagation.REQUIRED) public List<User> select(){ return userMapper.select(); } @Transactional(readOnly= true, propagation= Propagation.REQUIRES_NEW) public int delete(Integer id){ return userMapper.delete(id); }