记一次 @Transactional不生效的问题
生活随笔
收集整理的這篇文章主要介紹了
记一次 @Transactional不生效的问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
今天寫代碼的時候有一個service需要用到事務,故使用@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不生效的问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql分区、分表学习
- 下一篇: logback学习