spring boot controller設置 @Transactional 不回滾的解決辦法
在spring boot 中,使用事務非常簡單,直接在方法上麵加入@Transactional 就可以實現,以下是我的做法
@GetMapping("delete") @ResponseBody @Transactional public void delete(@RequestParam("id") int id){ try { //delete country this.repository.delete(id); if(id == 1){ throw Exception("測試事務"); } //delete city this.repository.deleteByCountryId(id); }catch (Exception e){ logger.error("delete false:" + e.getMessage()); return new MessageBean(101,"delete false"); } }
發現事務不回滾,即 this.repository.delete(id); 成功把數據刪除了。
原因:
默認spring事務隻在發生未被捕獲的 RuntimeException 時才回滾。
spring aop 異常捕獲原理:被攔截的方法需顯式拋出異常,並不能經任何處理,這樣aop代理才能捕獲到方法的異常,才能進行回滾,默認情況下aop隻捕獲 RuntimeException 的異常,但可以通過配置來捕獲特定的異常並回滾
換句話說在service的方法中不使用try catch 或者在catch中最後加上throw new runtimeexcetpion(),這樣程序異常時才能被aop捕獲進而回滾
解決方案:
方案1.例如service層處理事務,那麼service中的方法中不做異常捕獲,或者在catch語句中最後增加throw new RuntimeException()語句,以便讓aop捕獲異常再去回滾,並且在service上層(webservice客戶端,view層action)要繼續捕獲這個異常並處理
方案2.在service層方法的catch語句中增加:TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();語句,手動回滾,這樣上層就無需去處理異常
1 @GetMapping("delete") 2 @ResponseBody 3 @Transactional 4 public Object delete(@RequestParam("id") int id){ 5 if (id < 1){ 6 return new MessageBean(101,"parameter wrong: id = " + id) ; 7 } 8 try { 9 //delete country 10 this.countryRepository.delete(id); 11 //delete city 12 this.cityRepository.deleteByCountryId(id); 13 return new MessageBean(200,"delete success"); 14 }catch (Exception e){ 15 logger.error("delete false:" + e.getMessage()); 16 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); 17 return new MessageBean(101,"delete false"); 18 } 19 }
更多參考內容:https://www.roncoo.com/article/index
最後更新:2017-10-18 15:04:11
上一篇:
寫給想成為前端工程師的同學們 —— 前端工程師是做什麼的?
下一篇:
遭JBoss漏洞破壞23000台服務器“中招
Android係列教程之七:EditText使用詳解-包含很多教程上看不到的功能演示
《Hadoop與大數據挖掘》一2.5.4 Hadoop K-Means編程實現
2017年上半年最受關注度的幾大免費OA品牌
《vSphere性能設計:性能密集場景下CPU、內存、存儲及網絡的最佳設計實踐》一1.5.3 分布式資源調度
ASP.NET的14個熱點問題解答
數加:開啟數據智能時代 ——從CIO/CTO晉升到CDO
#文末福利|雲棲大會門票限時贈送# 10.11雲棲大會Clouder Lab “十分鍾搭建共享應用”,手把手教你Serverless架構下的應用實現
備案合並後;有毛用?
NanoXML組件解析xml簡單例子
在Chrome OS 上看到一些價值