首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >记一次 @Transactional不生效的问题

记一次 @Transactional不生效的问题

作者头像
allsmallpig
发布2021-02-12 10:04:31
发布2021-02-12 10:04:31
68500
代码可运行
举报
文章被收录于专栏:allsmallpi博客allsmallpi博客
运行总次数:0
代码可运行

今天写代码的时候有一个service需要用到事务,故使用@Transactional注解

代码语言:javascript
代码运行次数:0
运行
复制
@Transactional
Map<String, Object> joinTeam(Long teamId, Long userId) throws Exception;

这里抛出自己定义的异常来实现事务回滚

接口实现类方法如下

代码语言:javascript
代码运行次数:0
运行
复制
 public Map joinTeam(Long teamId, Long userId) throws Exception {
        Map 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文档,发现下面这段:

代码语言:javascript
代码运行次数:0
运行
复制
If no rules are relevant to the exception, it will be treated like DefaultTransactionAttribute (rolling back onruntime exceptions).

所以Transactional默认异常回滚是runtimeexcetion才回滚

excetion是所有异常的总称。 而runtimeexcetion是具体的某一个异常。

所以得将Transactional设置回滚异常为excetion

故将接口修改如下,这次再抛自定义异常就会回滚了

代码语言:javascript
代码运行次数:0
运行
复制
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
Map<String, Object> joinTeam(Long teamId, Long userId) throws Exception;
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018/01/10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档