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{ }