try catch与spring的事务回滚

前言:

将异常捕获,并且在catch块中不对事务做显式提交(或其他应该做的操作如关闭资源等)=生吞掉异常。

如果抛出runtime exception 并在你的业务方法中没有catch到的话,事务会回滚。
一般不需要在业务方法中catch异常,如果非要catch,在做完你想做的工作后(比如关闭文件等)一定要抛出runtime exception,否则spring会将你的操作commit,这样就会产生脏数据.所以你的catch代码是画蛇添足。

1.catch只打印异常,不抛出异常

try {
        数据库做添加订单表;
        int a=5/0;
        数据库减少库存;
        }catch (Exception e){
            e.printStackTrace();
        }

此方法会影响事务,此时数据库中订单数据会插入成功!因为Spring的事物的标准是RuntimeException。

2.catch打印异常,并抛出异常

try {
        数据库做添加订单表;
        int a=5/0;
        数据库减少库存;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException();
        }

此方法不会影响事务,因为抛出了RuntimeException。

原文地址:https://www.cnblogs.com/Neonuu/p/14692843.html