SpringBoot使用注解实现事务管理

conttoller 

    controller和普通的controller类一样, 不用改变

   @RequestMapping(value = "/path/{id}", method = RequestMethod.DELETE, produces = "application/json")
    @ResponseBody
    public Result delete(HttpServletRequest request,@PathVariable("id") Long id) {
        Result result = null;
        try {
            result = DeleteService.delete(id);
        } catch (Exception e) {
            result = Result.getFailResult("删除记录失败");//前台用来显示出错信息
        }
        return result;
    }

Service

   首先在方法上加上 @Transactional(rollbackFor = Exception.class)  , 然后在该方法后面加上 throws Exception ,

   为了不报错,我们还须 DeleteService 接口中对应的delete()方法签名修改为:

 

public void delete(Integer personid) throws Exception;

 

rollbackFor  该属性用于设置需要进行回滚的异常类数组,当方法中抛出指定异常数组中的异常时,则进行事务回滚。

 

@Service
public class DeleteServiceImp implements DeleteService {

   @Override
    @Transactional(rollbackFor = Exception.class)//设置检查时异常时回滚事务
    public Result delete(Long id) throws Exception {
        Result result = null;
        int num = myMapper.delete(id);
        int index = 0;
        if (0 < num) {
            index = anotherMapper.deleteById(id);
            if (0 < index) {
                result = Result.getSuccessResult("删除版本记录成功");
            } else {
                throw new Exception("删除版本记录失败"); //删除关联表失败时,抛出一个异常  用来触发回滚
            }
        } else {
            throw new Exception("删除项目失败"); //删除失败时, 抛出异常 用来触发回滚
        }

        return result;
    }
}

 最后在程序入口类 Application.java 上加上注解 @EnableTransactionManagement , 开启事务注解

 

参考:https://blog.youkuaiyun.com/yerenyuan_pku/article/details/52885041

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值