springboot事务回滚

默认spring事务只在发生未被捕获的 runtimeExcetpion时才回滚。  

   spring aop  异常捕获原理:被拦截的方法需显式抛出异常,并不能经任何处理,这样aop代理才能捕获到方法的异常,才能进行回滚,默认情况下aop只捕获runtimeException的异常,但可以通过 

1.异常不try { }catch (Exception e){ }  回滚

@Transactional

public ErrorInfotransactionaTest(String no) {

Goods goods=goodsMapper.selectByPrimaryKey(no);

    if(goods==null){

        return ErrorInfo.inputIsNull();

    }

    goods.setStatus(2);

    goodsMapper.updateByPrimaryKey(goods);

    transactionaTest01(goods);

    return  ErrorInfo.getSuccess();

}

public void transactionaTest01(Goods goods){

goods.setStatus(3);

    goodsMapper.updateByPrimaryKey(goods);

    int i=1/0;

}

2.异常try { }catch (Exception e){ },不回滚

@Transactional

public ErrorInfotransactionaTest(String no) {

Goods goods=goodsMapper.selectByPrimaryKey(no);

    if(goods==null){

return ErrorInfo.inputIsNull();

    }

goods.setStatus(2);

    goodsMapper.updateByPrimaryKey(goods);

    transactionaTest01(goods);

    return  ErrorInfo.getSuccess();

}

public void transactionaTest01(Goods goods){

goods.setStatus(3);

    goodsMapper.updateByPrimaryKey(goods);

    try {

        int i=1/0;       //捕获异常,不回滚

    }catch (Exception e){

}

}

3.异常try { }catch (Exception e){ } 且TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();回滚

@Override

@Transactional

public ErrorInfotransactionaTest(String no) {

Goods goods=goodsMapper.selectByPrimaryKey(no);

    if(goods==null){

return ErrorInfo.inputIsNull();

    }

goods.setStatus(2);

    goodsMapper.updateByPrimaryKey(goods);

    transactionaTest01(goods);

    return  ErrorInfo.getSuccess();

}

public void transactionaTest01(Goods goods){

goods.setStatus(3);

    goodsMapper.updateByPrimaryKey(goods);

    try {

        int i=1/0;

    }catch (Exception e){

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //虽然try了,手动回滚

或者

throw new RuntimeException();

    }

}

你可能感兴趣的:(springboot事务回滚)