SpringBoot使用注解实现事务管理
程序员文章站
2022-05-17 19:26:48
conttoller controller和普通的controller类一样, 不用改变 Service 首先在方法上加上 @Transactional(rollbackFor = Exception.class) , 然后在该方法后面加上 throws Exception , 为了不报错,我们还须 ......
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; } }
参考: