SpringBoot2.0 项目中使用事务

参考博客:

SpringBoot开启事务常见坑点

另外注意手动回滚事务需要

(1)在业务层方法上添加注解 @Transactional

(2)在需要回滚的地方添加代码:

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

示例:

    @Transactional
    public ResultBuilder userUpdate(JSONObject jsonObject) {
        try {
            UserInfo userInfo = new UserInfo();
            int count = userInfoMapper.updateUserInfo(userInfo);
            if (count != 1){
                logger.error("[userUpdate] updateUserInfo is fail");
                return new ResultBuilder(StatusCode.FAIL);
            }
            //修改密码的情况下进行Redis中token清除
            if (!StringUtils.isEmpty(password)){
                try {
                    redisTemplate.delete(Constants.TOKEN_REDIS_KEY_PRE + userId);
                }catch (Exception ex){
                    logger.error("[userUpdate] redis delete key exception", ex);
                    //手动回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw ex;
                }
            }
            return new ResultBuilder(StatusCode.SUCCESS);
        }catch (Exception e){
            logger.error("[userUpdate] error", e);
            return new ResultBuilder(StatusCode.FAIL);
        }
    }

 

posted @ 2019-04-09 14:20  一线大码  Views(1475)  Comments(0Edit  收藏  举报