Spring5源码(47)-@Transactional声明式事物(五)嵌套事物简介

简介: Spring5源码(47)-@Transactional声明式事物(五)嵌套事物简介


1.引

前面四节已经简单介绍了Spring的事物管理,当然都是基于单个Service单个方法调用下的、最简答的事物管理,还遗留了一些问题,例如事物嵌套处理、RollbackOnly属性说明等等,接下来的篇幅我们着重介绍Spring中的嵌套事物。在介绍之前先来回顾一下Spring中的事物传播特性,并通过一个简单的例子来看感受一下嵌套事物。

传播特性名称 说明
PROPAGATION_REQUIRED 如果当前没有事物,则新建一个事物;如果已经存在一个事物,则加入到这个事物中
PROPAGATION_SUPPORTS 支持当前事物,如果当前没有事物,则以非事物方式执行
PROPAGATION_MANDATORY 使用当前事物,如果当前没有事物,则抛出异常
PROPAGATION_REQUIRES_NEW 新建事物,如果当前已经存在事物,则挂起当前事物
PROPAGATION_NOT_SUPPORTED 以非事物方式执行,如果当前存在事物,则挂起当前事物
PROPAGATION_NEVER 以非事物方式执行,如果当前存在事物,则抛出异常
PROPAGATION_NESTED 如果当前存在事物,则在嵌套事物内执行;如果当前没有事物,则与PROPAGATION_REQUIRED传播特性相同

所谓嵌套事物,就是ServiceA调用了ServiceB的方法,不同的service之间互相进行方法调用,就可能会引发嵌套事物的问题。

2.事物嵌套的例子
  • Service

package com.lyc.cn.v2.day09;
public interface AccountService {
    void save() throws RuntimeException;
    void delete() throws RuntimeException;
}
package com.lyc.cn.v2.day09;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
public class AccountServiceImpl implements AccountService {
    private JdbcTemplate jdbcTemplate;
    private static String insert_sql = "insert into account(balance) values (100)";
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void save() throws RuntimeException {
        System.out.println("==调用AccountService的save方法\n");
        jdbcTemplate.update(insert_sql);
        throw new RuntimeException("==AccountService的save方法手动抛出异常");
    }
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void delete() throws RuntimeException {
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void beforeCommit(boolean readOnly) {
                System.out.println("==回调,事物提交之前");
                super.beforeCommit(readOnly);
            }
            @Override
            public void afterCommit() {
                System.out.println("==回调,事物提交之后");
                super.afterCommit();
            }
            @Override
            public void beforeCompletion() {
                super.beforeCompletion();
                System.out.println("==回调,事物完成之前");
            }
            @Override
            public void afterCompletion(int status) {
                super.afterCompletion(status);
                System.out.println("==回调,事物完成之后");
            }
        });
        System.out.println("==调用AccountService的dele方法\n");
        jdbcTemplate.update(insert_sql);
        throw new RuntimeException("==AccountService的delete方法手动抛出异常");
    }
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}
package com.lyc.cn.v2.day09;
public interface BankService  {
    void save() throws RuntimeException;
}
package com.lyc.cn.v2.day09;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
public class BankServiceImpl implements BankService {
    private PersonService personService;
    private AccountService accountService;
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void save() throws RuntimeException {
        System.out.println("==调用BankService的save方法\n");
        personService.save();
        accountService.save();
    }
    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }
    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }
}
package com.lyc.cn.v2.day09;
public interface PersonService {
    void save() throws RuntimeException;
}
package com.lyc.cn.v2.day09;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
public class PersonServiceImpl implements PersonService {
    private JdbcTemplate jdbcTemplate;
    private static String insert_sql = "insert into account(balance) values (100)";
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void save() throws RuntimeException {
        System.out.println("==调用PersonService的save方法\n");
        jdbcTemplate.update(insert_sql);
        //throw new RuntimeException("==PersonService手动抛出异常");
    }
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}

新建三个Service接口及其实现类,AccountService、BankService、PersonService。然后在BankService的save方法中调用了AccountService、PersonService的方法。

  • 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--开启tx注解-->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <!--事物管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/my_test?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="liyanchao1989@"/>
    </bean>
    <!--jdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--业务bean-->
    <bean id="accountService" class="com.lyc.cn.v2.day09.AccountServiceImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
    <bean id="personService" class="com.lyc.cn.v2.day09.PersonServiceImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
    <bean id="bankService" class="com.lyc.cn.v2.day09.BankServiceImpl">
        <property name="personService" ref="personService"/>
        <property name="accountService" ref="accountService"/>
    </bean>
    <bean id="myTransactionService" class="com.lyc.cn.v2.day09.MyTransactionService">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
</beans>
  • 测试类及结果

@Test
public void test2() {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("v2/day09.xml");
    BankService service = ctx.getBean("bankService", BankService.class);
    service.save();
}

==创建了名为:[com.lyc.cn.v2.day09.BankServiceImpl.save]的事物
==调用BankService的save方法
==创建了名为:[com.lyc.cn.v2.day09.PersonServiceImpl.save]的事物
==调用PersonService的save方法
==创建了名为:[com.lyc.cn.v2.day09.AccountServiceImpl.save]的事物
==调用AccountService的save方法
==准备回滚com.lyc.cn.v2.day09.AccountServiceImpl.save
==当前事物并非独立事物,且RollbackOnly为true
==准备回滚com.lyc.cn.v2.day09.BankServiceImpl.save
java.lang.RuntimeException: ==AccountService的save方法手动抛出异常
3.嵌套事物的处理简介

回顾一下前面讲的创建事物的过程,其中有:

// 2.如果当前已经存在事物
// 重点:
// 如果当前已经存在启动的事物,则根据本次要新建的事物传播特性进行评估,以决定对新事物的后续处理
if (isExistingTransaction(transaction)) {
    // Existing transaction found -> check propagation behavior to find out how to behave.
    return handleExistingTransaction(definition, transaction, debugEnabled);
}

这里我们没有分析,因为从这开始就要涉及到事物的嵌套处理了(在AbstractPlatformTransactionManager类的getTransaction方法中)。

因为我们在在BankService的save方法中调用了AccountService、PersonService的方法。那么当BankService调用到另外两个Servcie方法的时候,因为当前已经存在事物(BankService),那么接下来就要根据新事物的传播特性,以决定下一步的处理了。先来感受一下处理过程:

private TransactionStatus handleExistingTransaction(
            TransactionDefinition definition,
            Object transaction,
            boolean debugEnabled) throws TransactionException {
    // 1.PROPAGATION_NEVER --> 以非事物方式执行,如果当前存在事物,则抛出异常。
    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NEVER) {
        throw new IllegalTransactionStateException("Existing transaction found for transaction marked with propagation 'never'");
    }
    // 2.以非事物方式执行,如果当前存在事物,则挂起当前事物。
    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) {
        if (debugEnabled) { logger.debug("Suspending current transaction");}
        // 重点:挂起已有事物
        Object suspendedResources = suspend(transaction);
        boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
        // 创建新事物,注意:transaction参数为null,所以这里创建的不是一个真正的事物
        return prepareTransactionStatus(
                definition,
                null,
                false,
                newSynchronization,
                debugEnabled,
                suspendedResources);
    }
    //3.新建事物,如果当前已经存在事物,则挂起当前事物。
    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) {
        if (debugEnabled) {
            logger.debug("Suspending current transaction, creating new transaction with name [" + definition.getName() + "]");
        }
        // 挂起已有事物
        SuspendedResourcesHolder suspendedResources = suspend(transaction);
        try {
            boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
            // 创建事物
            DefaultTransactionStatus status = newTransactionStatus(
                    definition,
                    transaction,
                    true,
                    newSynchronization,
                    debugEnabled,
                    suspendedResources);
            // 开启事物
            doBegin(transaction, definition);
            // 初始化事物同步属性
            prepareSynchronization(status, definition);
            return status;
        }
        catch (RuntimeException | Error beginEx) {
            resumeAfterBeginException(transaction, suspendedResources, beginEx);
            throw beginEx;
        }
    }
    // 4.如果当前存在事物,则在嵌套事物内执行;如果当前没有事物,则与PROPAGATION_REQUIRED传播特性相同
    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
        // 如果不允许嵌套事物,则抛出异常
        if (!isNestedTransactionAllowed()) {
            throw new NestedTransactionNotSupportedException("Transaction manager does not allow nested transactions by default - " +
                    "specify 'nestedTransactionAllowed' property with value 'true'");
        }
        if (debugEnabled) {
            logger.debug("Creating nested transaction with name [" + definition.getName() + "]");
        }
        /**
         * 下面对JtaTransactionManager和AbstractPlatformTransactionManager分别进行处理
         */
        // useSavepointForNestedTransaction(),是否为嵌套事务使用保存点
        // 1.对于JtaTransactionManager-->返回false
        // 2.对于AbstractPlatformTransactionManager-->返回true
        if (useSavepointForNestedTransaction()) {
            // Create savepoint within existing Spring-managed transaction,
            // through the SavepointManager API implemented by TransactionStatus.
            // Usually uses JDBC 3.0 savepoints. Never activates Spring synchronization.
            // 创建保存点在现有spring管理事务,通过TransactionStatus SavepointManager API实现。
            // 通常使用JDBC 3.0保存点。永远不要激活Spring同步。
            DefaultTransactionStatus status = prepareTransactionStatus(definition,transaction,
                    false,
                    false,
                    debugEnabled,
                    null);
            // 创建保存点
            status.createAndHoldSavepoint();
            return status;
        }
        else {
            // Nested transaction through nested begin and commit/rollback calls.
            // Usually only for JTA: Spring synchronization might get activated here
            // in case of a pre-existing JTA transaction.
            // 通过嵌套的开始,提交调用,及回滚调用进行嵌套事务。
            // 只对JTA有效,如果已经存在JTA事务,这里可能会激活Spring同步。
            boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
            DefaultTransactionStatus status = newTransactionStatus(
                    definition,
                    transaction,
                    true,
                    newSynchronization,
                    debugEnabled,
                    null);
            doBegin(transaction, definition);
            prepareSynchronization(status, definition);
            return status;
        }
    }
    // Assumably PROPAGATION_SUPPORTS or PROPAGATION_REQUIRED.
    // 处理PROPAGATION_SUPPORTS和PROPAGATION_REQUIRED两种传播特性
    // PROPAGATION_REQUIRED --> 如果当前没有事物,则新建一个事物;如果已经存在一个事物,则加入到这个事物中。
    // PROPAGATION_SUPPORTS --> 支持当前事物,如果当前没有事物,则以非事物方式执行。
    if (debugEnabled) {
        logger.debug("Participating in existing transaction");
    }
    // 对于PROPAGATION_SUPPORTS和PROPAGATION_REQUIRED
    // 新事物参与已有事物时,是否验证已有事物.此属性值默认为false;
    // 如开启将验证新事物和已有事物的隔离级别和事物只读属性是否相同
    if (isValidateExistingTransaction()) {
        // 验证事物隔离级别
        // 如果当前事物的隔离级别不为默认隔离级别,则比较当前事物隔离级别与已有事物隔离级别,
        // 如不同,则抛出事物隔离级别不兼容异常
        if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
            Integer currentIsolationLevel = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();
            if (currentIsolationLevel == null || currentIsolationLevel != definition.getIsolationLevel()) {
                Constants isoConstants = DefaultTransactionDefinition.constants;
                throw new IllegalTransactionStateException("Participating transaction with definition [" +
                        definition + "] specifies isolation level which is incompatible with existing transaction: " +
                        (currentIsolationLevel != null ?
                                isoConstants.toCode(currentIsolationLevel, DefaultTransactionDefinition.PREFIX_ISOLATION) :
                                "(unknown)"));
            }
        }
        // 验证事物只读属性
        // 如果当前事物可写,但是已有的事物是只读,则抛出异常
        if (!definition.isReadOnly()) {
            if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
                throw new IllegalTransactionStateException("Participating transaction with definition [" +
                        definition + "] is not marked as read-only but existing transaction is");
            }
        }
    }
    boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
    return prepareTransactionStatus(definition, transaction, false, newSynchronization, debugEnabled, null);
}

在该方法中,对于Spring提供的传播特性分别做了不同的处理,那么接下来我们会对这些传播特性一一分析,包括事物的后续处理、事物的回滚等。



目录
相关文章
|
1月前
|
Java 数据库 Spring
【spring(四)】Spring事务管理和@Transactional注解
【spring(四)】Spring事务管理和@Transactional注解
|
2天前
|
XML 人工智能 Java
Spring Bean名称生成规则(含源码解析、自定义Spring Bean名称方式)
Spring Bean名称生成规则(含源码解析、自定义Spring Bean名称方式)
|
3天前
|
消息中间件 Java Nacos
第三章 Spring Cloud简介
第三章 Spring Cloud简介
11 0
|
9天前
|
Java 关系型数据库 MySQL
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
UWB (ULTRA WIDE BAND, UWB) 技术是一种无线载波通讯技术,它不采用正弦载波,而是利用纳秒级的非正弦波窄脉冲传输数据,因此其所占的频谱范围很宽。一套UWB精确定位系统,最高定位精度可达10cm,具有高精度,高动态,高容量,低功耗的应用。
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
|
1月前
|
Java Spring
使用spring实现邮件的发送(含测试,源码,注释)
使用spring实现邮件的发送(含测试,源码,注释)
7 0
|
1月前
|
Java Spring 容器
【Spring源码】单例创建期间进行同步可能会导致死锁?
通过这个标题我们就可以思考本次的阅读线索了,看起来可以学到不少东西。1. 旧代码的死锁是怎么产生的。2. 贡献者通过改变什么来解决本次PR的问题呢?而阅读线索2的答案也显而易见,就是上文提到的通过后台线程来创建Micrometer单例...
42 3
|
存储 缓存 Java
Spring 缓存抽象简介|学习笔记
快速学习 Spring 缓存抽象简介
77 0
|
XML 开发框架 监控
Spring Boot 简介|学习笔记
快速学习 Spring Boot简介
105 0
|
前端开发 Java 程序员
01_spring_ 简介| 学习笔记
快速学习 01_spring_ 简介
|
29天前
|
Java 应用服务中间件 Maven
SpringBoot 项目瘦身指南
SpringBoot 项目瘦身指南
43 0