什麼是事務?
所謂事務是用戶定義的一個數據庫操作序列,這些操作要麼全做,要麼全不做,是一個不可分割的工作單位
事務的特性?
原子性:要麼全做,要麼全不做。
一致性:說的是全部做,和全不做,這時數據庫處於一致性,如果一個做,一個不做,就認爲不一致。
隔離性:一個事務的執行不能被其他事務干擾,即一個事務的內部操作以及使用的數據對其他併發事務是隔離的。
持續性:一個事務一旦提交,它對數據庫中數據的改變就應該是永久行的。
如何聲明事務管理
基於TransactionProxyFactoryBean方式
基於tx/aop配置切面增強事務
基於註解
本篇主要說下,基於tx/aop配置切面增強事務。
1:引入命名空間
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
2:tx\aop核心配置
<!-- 配置事務屬性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRES_NEW" />
<tx:method name="update*" propagation="REQUIRES_NEW" />
<tx:method name="delete*" propagation="REQUIRES_NEW" />
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置事務切入點,以及把事務切入點和事務屬性關聯起來 -->
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(* com.yc.service.*.*(..))"
id="ServicePointcut" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="ServicePointcut" />
</aop:config>
在標籤中,常見屬性及其說明如下,其中,除了name屬性是必選外,其他都是可選的:
屬性 | 說明 | 默認 | 允許值 |
---|---|---|---|
name | 匹配方法名 | 必須聲明,至少爲* | 可使用*通配符 |
propagation | 事務傳播行爲 | REQUIRED | REQUIRED,SUPPORTS和MANDATORY和REQUIRES_NEW和NOT_SUPPORTED和NEVER和NESTED |
read-only | 設置當前事務是否只讀 | false | true,false |
isolation | 事務隔離級別 | DEFAULT | READ_UNCOMMITTED和READ_COMMITTED和REPEATABLE_READ和SERIALIZABLE |
timeout | 設置事務的超時時間 | -1 | 默認由頂層事務系統決定 |
rollback-for | 內容爲異常名,表示當拋出這些異常時事務回滾,可以用逗號分隔配置多個 | 無默認值 | 可以使用異常名稱的片段進行匹配如ception等 |
no-rollback-for | 內容爲異常名,表示當拋出這些異常時繼續提交事務,可以用逗號分隔配置多個 | 無默認值 | 可以使用異常名稱的片段進行匹配如ception等 |