SpringBoot事務使用及回滾實現代碼詳解
Springboot中事務的使用:
1、啟動類加上@EnableTransactionManagement注解,開啟事務支持(其實默認是開啟的)。
2、在使用事務的public(只有public支持事務)方法(或者類-相當于該類的所有public方法都使用)加上@Transactional注解。
在實際使用中一般是在service中使用@Transactional,那么對于controller->service流程中:
如果controller未開啟事務,service中開始了事務,service成功執行,controller在之后的運行中出現異常(錯誤),不會自動回滾。
也就是說,只有在開啟事務的方法中出現異常(默認只有非檢測性異常才生效-RuntimeException )(錯誤-Error)才會自動回滾。
如果想要對拋出的任何異常都進行自動回滾(而不是只針對RuntimeException),只需要在使用@Transactional(rollbackFor = Exception.class)即可。
開啟事務的方法中事務回滾的情況:
①未發現的異常,程序運行過程中自動拋出RuntimeException或者其子類,程序終止,自動回滾。
②使用TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();進行手動回滾。
③注意:如果在try-catch語句中對可能出現的異常(RuntimeException)進行了處理,沒有再手動throw異常,spring認為該方法成功執行,不會進行回滾,此時需要調用②中方法進行手動回滾,如下圖:
另外,如果try-catch語句在finally中進行了return操作,那么catch中手動拋出的異常也會被覆蓋,同樣不會自動回滾。
//不會自動回滾try{ throw new RuntimeException();}catch(RuntimeException e){ e.printStackTrace();}finally{}//會自動回滾try{ throw new RuntimeException();}catch(RuntimeException e){ e.printStackTrace(); throw new RuntimeException();}finally{}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: