关于事务传播机制与嵌套事务

Spring 事务传播属性如下

   PROPAGATION_REQUIRED--支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。

  PROPAGATION_SUPPORTS--支持当前事务,如果当前没有事务,就以非事务方式执行。

  PROPAGATION_MANDATORY--支持当前事务,如果当前没有事务,就抛出异常。

  PROPAGATION_REQUIRES_NEW--新建事务,如果当前存在事务,把当前事务挂起。

  PROPAGATION_NOT_SUPPORTED--以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。

   PROPAGATION_NEVER--以非事务方式执行,如果当前存在事务,则抛出异常。

   PROPAGATION_NESTED--

拿以下代码分析Spring 嵌套事务

复制代码

    ServiceA { 


        void methodA() { 

            ServiceB.methodB(); 

        } 


    } 


    ServiceB { 


        void methodB() { 

        } 


    } 

复制代码

案例1,ServiceB.methodB的事务级别定义为PROPAGATION_REQUIRED,

  1、如果ServiceA.methodA已经起了事务,这时调用ServiceB.methodB,会共用同一个事务,如果出现异常,ServiceA.methodA和ServiceB.methodB作为一个整体都将一起回滚。

  2、如果ServiceA.methodA没有事务,ServiceB.methodB就会为自己分配一个事务。ServiceA.methodA中是不受事务控制的。如果出现异常,ServiceB.methodB不会引起ServiceA.methodA的回滚。

案例2,ServiceA.methodA的事务级别PROPAGATION_REQUIRED,ServiceB.methodB的事务级别PROPAGATION_REQUIRES_NEW,

调用ServiceB.methodB,ServiceA.methodA所在的事务就会挂起,ServiceB.methodB会起一个新的事务。

1、如果ServiceB.methodB已经提交,那么ServiceA.methodA失败回滚,ServiceB.methodB是不会回滚的。

2、如果ServiceB.methodB失败回滚,如果他抛出的异常被ServiceA.methodA的try..catch捕获并处理,ServiceA.methodA事务仍然可能提交;如果他抛出的异常未被ServiceA.methodA捕获处理,ServiceA.methodA事务将回滚。

案例3,ServiceA.methodA的事务级别为PROPAGATION_REQUIRED,ServiceB.methodB的事务级别为PROPAGATION_NESTED,

调用ServiceB.methodB的时候,ServiceA.methodA所在的事务就会挂起,ServiceB.methodB会起一个新的子事务并设置savepoint

1、如果ServiceB.methodB已经提交,那么ServiceA.methodA失败回滚,ServiceB.methodB也将回滚。

2、如果ServiceB.methodB失败回滚,如果他抛出的异常被ServiceA.methodA的try..catch捕获并处理,ServiceA.methodA事务仍然可能提交;如果他抛出的异常未被ServiceA.methodA捕获处理,ServiceA.methodA事务将回滚。

你可能感兴趣的:(关于事务传播机制与嵌套事务)