zoukankan      html  css  js  c++  java
  • 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.csdn.net/yerenyuan_pku/article/details/52885041

  • 相关阅读:
    工厂方法模式(2)
    单例模式(1)
    数组中任意位置添加数组
    六中设计模式中的原则总结
    开闭原则(设计模式6)
    迪米特法则(设计模式5)
    接口隔离原则(设计模式4)
    依赖倒置原则(设计模式3)
    里氏替换原则(设计模式原则2)
    相似图片搜索的原理(二) (转载)
  • 原文地址:https://www.cnblogs.com/gczmn/p/10179331.html
Copyright © 2011-2022 走看看