1. 程式人生 > >經驗總結55--spring開啟事務回滾

經驗總結55--spring開啟事務回滾

使用spring的@Transactional註解,異常時,進行事務回滾。

1.引用

xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd

2.開啟事務

<tx:annotation-driven transaction-manager="transactionManager" />

3.在業務層的方法使用註解

@Transactional

注,使用最新的spring框架,丟擲的異常都可以進行事務回滾。

若做介面,捕獲異常後,統一返回值,不向最外層丟擲異常,就無法使用事務回滾機制。

但spring提供手動事務回滾機制。

在捕獲異常時,使用程式碼:TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

這樣就可以主動回滾。