事务 @Transactional 的 Propagation.REQUIRES_NEW

小经验:
同一个业务类里面 , 即使声明为 Propagation.REQUIRES_NEW也不会新启一个事务。必须调用另一个类的Propagation.REQUIRES_NEW方法才行。

如下代码:

@Service
public class A {

    @Autowired
    private OrderApplyMapper orderApplyMapper;

    @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = Exception.class)
    public int testB(OrderApply order) {
        return orderApplyMapper.save(order);
    }

    @Transactional
    public void testA(OrderApply order) {
        System.out.println("1111111111111");
        testB(order);
        System.out.println("2222222222222");
        throw new RuntimeException();
    }

}

这2个方法在同一个类中,本身预期结果是testB方法执行成功,testA方法回滚。实际结果是testB也会被回滚。

如果想使 Propagation.REQUIRES_NEW 生效,则需要把testB这个方法单独放到别的类中,然后调用过来。

具体为什么会这样,没有深究,写下来记录一下。

你可能感兴趣的:(Spring)