Spring:Spring嵌套事務方式

Spring遇到嵌套事務時,怎麼實現

實驗時卻遇到一個奇怪的問題:spring


一、當ServiceA.a()方法調用ServiceB.b()方法時,內層事務提交和回滾,都不受外層事務提交或回滾的影響。spa


二、當ServiceA.a()方法調用ServiceA.c()方法時,內層事務不能正確地提交或回滾。.net

 

以下:code

xxxServiceA類中,有以下兩個方法。blog

 

@Transactional method_One() { method_Two(); } @Transactional(propagation = Propagation.REQUIRES_NEW) method_Two(){ //do something
}

 

沒有找到相似creating new transaction的輸出,同一個Service類中,spring並不從新建立新事務,若是是兩不一樣的Service,就會建立新事務了。事務

 

xxxServiceA類:io

@Transactional method_One() { method_Two(); }

xxxServiceB類:class

@Transactional(propagation = Propagation.REQUIRES_NEW) method_Two(){ //do something
}

Propagation.REQUIRES_NEW生效建立了一個新事務方法

 

讓事務起做用,遇到錯誤進行回滾,應該注意的事項

第一種狀況:同一個類中 一個方法無嵌套方法im

若是方法名上加上@Transactional註解,方法內不要用try catch ;若是必需要用try catch ,則catch中必須用throw new RuntimeException()。不然事務不起做用。


第二種狀況:同一個類中 方法A嵌套方法B
方法A有@Transactional,方法內都沒有try catch,事務起做用。
方法A有@Transactional和try catch,而且catch中用throw new RuntimeException(),事務起做用。


第三種狀況:不一樣類中方法C嵌套方法B
方法B上加上@Transactional註解,方法內不要用try catch ;若是必需要用try catch ,則catch中必須用throw new RuntimeException()。不然方法B的事務不起做用。
方法C上加上@Transactional註解,方法內不要用try catch ;若是必需要用try catch ,則catch中必須用throw new RuntimeException(),此時方法B怎麼寫都行。不然方法C的事務不起做用。

 

 

文章轉載至:https://blog.csdn.net/m0_37701381/article/details/85066711

相關文章
相關標籤/搜索