springboot(十一)事务

14 阅读1分钟

事务

事务要么都成功,要么都失败

没有使用事务

    @Transactional
    public void transactional(){
        //1. 新增
        //2. 异常
        //3. 修改
        //4. 事务要么都成功,要么都失败,因为中间过程中有异常,所以会回滚,
        User user = new User();
        user.setName("ccc");
        user.setAge(10);
        userMapper.insert(user);

        int newId = 100 / 0; //异常
        log.info("newId"+newId);
        User user2 = new User();
        user2.setId(1);
        user2.setName("111111");
        userMapper.updateByPrimaryKeySelective(user2);
    }

请求前数据

image.png

请求后数据

image.png

使用事务

@Transactional

    @Transactional
    public void transactional(){
        //1. 新增
        //2. 异常
        //3. 修改
        //4. 事务要么都成功,要么都失败,因为中间过程中有异常,所以会回滚,
        User user = new User();
        user.setName("ccc");
        user.setAge(10);
        userMapper.insert(user);

        int newId = 100 / 0; //异常
        log.info("newId"+newId);
        User user2 = new User();
        user2.setId(1);
        user2.setName("111111");
        userMapper.updateByPrimaryKeySelective(user2);
    }

请求前数据

image.png

image.png

处理对应的异常

image.png

exception/GraceExceptionHandler

    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public JSONResult returnMyCustomException(ArithmeticException e){
        return JSONResult.errorException(e.getMessage());
    }

处理后

image.png