1. 程式人生 > 實用技巧 >宣告式事務

宣告式事務

Spring宣告式事務

目標

從事務角度:一個事務方法中包含的多個數據庫操作,要麼一起提交、要麼一起回滾.也就是說事務方法中的多個數據庫操作,有任何一個失敗,整個事務全部回滾.

從宣告式角度:由Spring來全面接管資料庫事務.用宣告式代替程式設計式(解耦).

思路

操作步驟

1、匯入座標

<!-- AOP 所需依賴 -->
 <dependency> 
    <groupId>org.aspectj</groupId> 
    <artifactId>aspectjweaver</artifactId> 
</
dependency> <!-- AOP 所需依賴 --> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> </dependency>

2、修改配置檔案

  • 配置事務管理器
  • 配置AOP
  • 配置事務管理器

spring-mabatis.xml增加配置如下:

<!-- 3\配置 MapperScannerConfigurer -->
    <!-- 把 MyBatis 建立的 Mapper 介面型別的代理物件掃描到 IOC 容器中 
--> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 使用 basePackage 屬性指定 Mapper 介面所在包 --> <property name="basePackage" value="com.adom.mapper"/> </bean> <!--3\配置Spring框架宣告式事務管理--> <!--
配置事務管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--配置AOP增強--> <!-- 配置 AOP --> <aop:config> <!-- 配置切入點表示式 --> <aop:pointcut expression="execution(* *..*Service.*(..))" id="txPointCut"/> <!-- 將事務通知和切入點表示式關聯到一起 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/> </aop:config> <!-- 配置事務通知 --> <!-- id 屬性用於在 aop:advisor 中引用事務通知 --> <!-- transaction-manager 屬性用於引用事務管理器,如果事務管理器的 bean 的 id 正好是 transactionManager,可以省略這個屬性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- name 屬性指定當前要配置的事務方法的方法名 --> <!-- 查詢的方法通常設定為只讀,便於資料庫根據只讀屬性進行相關效能優化 --> <tx:method name="get*" read-only="true"/> <tx:method name="query*" read-only="true"/> <tx:method name="find*" read-only="true"/> <tx:method name="count*" read-only="true"/> <!-- 增刪改方法另外配置 --> <!-- propagation 屬性配置事務方法的傳播行為 --> <!-- 預設值:REQUIRED 表示:當前方法必須執行在事務中,如果沒有事務,則開 啟事務,在自己的事務中執行。如果已經有了已開啟的事務,則在當前事務中執行。 有可能 和其他方法共用同一個事務。 --> <!-- 建議值:REQUIRES_NEW 表示:當前方法必須執行在事務中,如果沒有事務, 則開啟事務,在自己的事務中執行。 和REQUIRED的區別是就算現在已經有了已開啟的事務, 也一定要開啟自己的事務, 避免和其他方法共用同一個事務。 --> <!-- rollback-for 屬性配置回滾的異常 --> <!-- 預設值:執行時異常 --> <!-- 建議值:編譯時異常+執行時異常 --> <tx:method name="save*" rollback-for="java.lang.Exception" propagation="REQUIRES_NEW"/> <tx:method name="remove*" rollback-for="java.lang.Exception" propagation="REQUIRES_NEW"/> <tx:method name="update*" rollback-for="java.lang.Exception" propagation="REQUIRES_NEW"/> </tx:attributes> </tx:advice>