spring @Transactional事務失效


 不開事務幾種情形

① @Transactional寫在了private方法上

org.springframework.transaction.interceptor.AbstractFallbackTransactionAttributeSource#computeTransactionAttribute

 

② 普通方法doTask3調用同一個類中有注解的方法doTask3Out, 並沒有開啟事務

 

 

參考:

https://www.cnblogs.com/milton/p/6046699.html

https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#transaction-declarative-annotations

https://www.ibm.com/developerworks/cn/java/j-master-spring-transactional-use/index.html

同一個事務中會做 多個Dao操作,它們使用的jdbc connection是同一個,因為在同一個線程中,connection id可以保存在ThreadLocal中

 

③異步線程是否開始新事務,和非異步的主線程有關系嗎

    @Transactional
public void doTask1() {
doTask2In();

//此處方法3上面的注解失效了!!!!
new Thread(()->{doTask3Out();}).start();
}
這個情況和情形2類似. 多線程編程時要注意, 沒事別亂開線程

解決方法是使用AspectJ攔截事務, 不使用spring 默認的aop攔截事務



事務開始與連接獲取的源碼分析
org.springframework.jdbc.datasource.DataSourceTransactionManager#doBegin
org.springframework.transaction.annotation.Isolation中定義了幾個事務的隔離級別:默認,讀已提交 , 讀未提交,序列化



多數據源配置: https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#tx-multiple-tx-mgrs-with-attransactional

 

 

Spring團隊的建議是你在具體的類(或類的方法)上使用 @Transactional 注解,而不要使用在類所要實現的任何接口上。你當然可以在接口上使用 @Transactional 注解,但是這將只能當你設置了基於接口的代理時它才生效。因為注解是 不能繼承 的,這就意味着如果你正在使用基於類的代理時,那么事務的設置將不能被基於類的代理所識別,而且對象也將不會被事務代理所包裝(將被確認為嚴重的)。因 此,請接受Spring團隊的建議並且在具體的類上使用 @Transactional 注解。

 

參考

Fescar分布式事務 https://my.oschina.net/keking/blog/3011509

 

 

 






 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM