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

  • 相关阅读:
    四、创建多线程、数据共享
    operator函数操作符
    三、线程传参
    二、线程创建、结束
    一、并发、进程、线程概念
    bagging和boosting的区别
    ID3,C4.5和CART三种决策树的区别
    7创建型模式之建造者模式
    6创建型模式之工厂模式与抽象工厂模式
    5创建型模式之简单工厂模式
  • 原文地址:https://www.cnblogs.com/gczmn/p/10179331.html
Copyright © 2011-2022 走看看