日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

记一次 @Transactional不生效的问题

發布時間:2024/2/28 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 记一次 @Transactional不生效的问题 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

今天寫代碼的時候有一個service需要用到事務,故使用@Transactional注解

@Transactional Map<String, Object> joinTeam(Long teamId, Long userId) throws Exception;

這里拋出自己定義的異常來實現事務回滾

接口實現類方法如下

public Map<String, Object> joinTeam(Long teamId, Long userId) throws Exception {Map<String, Object> result = new HashMap<>();Team team = teamService.getTeamById(teamId);//添加組隊成員TeamMember member = new TeamMember();member.setUserId(userId);member.setTeamId(teamId);teamMemberDao.saveTeamMember(member);//更新組隊人數team.setCurrentSignup(team.getCurrentSignup() + 1);Long count = teamService.updateTeamCurrentSignup(team);int i = 0;while (count == 0) {if (i >= 3) {throw new BaseException(BaseException.OPTIMISTIC_LOCK);}team = teamService.getTeamById(teamId);team.setCurrentSignup(team.getCurrentSignup() + 1);count = teamService.updateTeamCurrentSignup(team);i++;}result.put("success", true);result.put("message", "加入成功!");throw new Exception(BaseException.OPTIMISTIC_LOCK);}

teamMemberDao.saveTeamMember(member)?與?count = teamService.updateTeamCurrentSignup(team)?兩個修改庫操作,需要?teamService.updateTeamCurrentSignup(team)?拋異常來控制?teamMemberDao.saveTeamMember(member)?的數據回滾

但是結尾拋異常數據并不回滾,很是糟心。

于是查看Spring的Transactional的API文檔,發現下面這段:

If no rules are relevant?to?the?exception,?it?will be treated like DefaultTransactionAttribute (rolling?back?onruntime exceptions).

所以Transactional默認異常回滾是runtimeexcetion才回滾

excetion是所有異常的總稱。
而runtimeexcetion是具體的某一個異常。

所以得將Transactional設置回滾異常為excetion

故將接口修改如下,這次再拋自定義異常就會回滾了

@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class) Map<String, Object> joinTeam(Long teamId, Long userId) throws Exception;
  • 1 天

總結

以上是生活随笔為你收集整理的记一次 @Transactional不生效的问题的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。