@Transactional 事务实现机制
在应用系统调用声明了 @Transactional
的目标方法时,Spring Framework 默认使用 AOP 代理,在代码运行时生成一个代理对象,根据 @Transactional
的属性配置信息,这个代理对象决定该声明 @Transactional
的目标方法是否由拦截器 TransactionInterceptor
来使用拦截,在 TransactionInterceptor
拦截时,会在目标方法开始执行之前创建并加入事务,并执行目标方法的逻辑, 最后根据执行情况是否出现异常,利用抽象事务管理器 AbstractPlatformTransactionManager
操作数据源 DataSource
提交或回滚事务。
场景一:同一个service中,父方法调用了子方法都使用了@Transactional方法,则父方法发生异常时会整体回滚:
官方解释如下:
In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional.
大概意思:在默认的代理模式下,只有目标方法由外部调用,才能被 Spring 的事务拦截器拦截。在同一个类中的两个方法直接调用,是不会被 Spring 的事务拦截器拦截,就像上面的 save 方法直接调用了同一个类中的 method1方法,method1 方法不会被 Spring 的事务拦截器拦截。
场景二:一个父方法中包含了多个子方法,如发生异常无需回滚异常前执行结果的情况,则需要将子方法写入一个新的service,并将子方法@Transactional 的 propagation 属性设置为 Propagation.REQUIRES_NEW。
这样父方法的执行过程变更为:
首先创建了 父方法 的事务,执行到子方法,暂停了 save 方法的事务,重新创建了 子方法 的事务,接着 子方法 的事务提交,之后发生异常, 父方法 的事务回滚。
原文链接:https://blog.csdn.net/nextyu/article/details/78669997
本文根据博主个人需要整理保留个人理解部分。