美文网首页springboot
Spring Boot学习笔记三:事务管理

Spring Boot学习笔记三:事务管理

作者: 神小六 | 来源:发表于2020-03-12 14:09 被阅读0次

前面我们已经配置好了JPA,那么为了保证数据的一致性,我们就要用到事务控制。
在springboot上使用事务其实很简单,就一个注解@Transactional,那么就来试试吧
首先写个方法

    @RequestMapping("/save")
    @Transactional
    public void save(String name,Integer age) {
        User user = new User();
        user.setAge(age);
        user.setName(name);
        userRepository.save(user);
        throw new NullPointerException();
    }

接着去postman执行一下



去数据库看下有没有新增数据


image.png
没有新增数据说明事务回滚。我们也可以在类上直接添加注解,那么所有的方法都进行事务的管理。
其中Spring的默认的事务规则是遇到运行异常(RuntimeException及其子类)和程序错误(Error)才会进行事务回滚,当我们遇到SQLException(检测异常)时事务不回滚
    @RequestMapping("/save")
    @Transactional
    public void save(String name,Integer age) throws SQLException {
        User user = new User();
        user.setAge(age);
        user.setName(name);
        userRepository.save(user);
        throw new SQLException("发生异常了!!!");
    }
image.png
image.png

数据添加了,说明事务没有回滚,那么我们可以使用rollbackOn属性,表示当该方法中抛出指定的异常时数据回滚

    @RequestMapping("/save")
    @Transactional(rollbackOn = Exception.class)
    public void save(String name,Integer age) throws SQLException {
        User user = new User();
        user.setAge(age);
        user.setName(name);
        userRepository.save(user);
        throw new SQLException("发生异常了!!!");
    }

执行一下


image.png
image.png

数据没有增加,说明回滚了
注解还有个属性叫dontRollbackOn,表示当该方法中抛出指定的异常时数据不回滚
还有在业务层捕捉异常后,发现事务不生效。例如

    @RequestMapping("/save")
    @Transactional(rollbackOn = Exception.class)
    public void save(String name,Integer age){
        User user = new User();
        user.setAge(age);
        user.setName(name);
        userRepository.save(user);
        try {
            throw new SQLException("发生异常了!!!");
        } catch (Exception e){
            e.printStackTrace();
        }
    }

执行一下


image.png

事务没有回滚,我们把异常统一抛出,例如

    @RequestMapping("/save")
    @Transactional(rollbackOn = Exception.class)
    public void save(String name,Integer age) throws Exception {
        User user = new User();
        user.setAge(age);
        user.setName(name);
        userRepository.save(user);
        throw new SQLException("发生异常了!!!");
    }

这样事务就回滚了
参考资料:https://blog.csdn.net/cowbin2012/article/details/90751044
其中这里rollbackFor 属性没有了,改成了rollbackOn

相关文章

网友评论

    本文标题:Spring Boot学习笔记三:事务管理

    本文链接:https://www.haomeiwen.com/subject/lrjujhtx.html