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.csdn.net/yerenyuan_pku/article/details/52885041