Java 后端 / 系统课时

理解默认回滚规则

理解默认回滚规则

事务方法抛出异常,并不代表事务一定回滚。本课用一个可直接运行的 Spring Boot + H2 实验验证默认回滚规则,并说明 checked exception、异常被内部捕获以及事务代理未生效时为什么可能得到不同结果。

学习目标

  • 区分 RuntimeException、Error 与 checked exception 的默认回滚行为
  • 用可运行实验验证异常类型与最终提交结果的对应关系
  • 判断异常传播和事务代理边界是否会改变预期结果

默认规则如何判定

未声明自定义回滚规则时,Spring 的 @Transactional 默认对 RuntimeException 及其子类、Error 及其子类执行回滚;checked exception 默认不触发回滚。判断依据是事务方法最终向事务拦截器抛出的实际异常类型,而不是类名中是否包含 Exception,也与方法签名是否声明 throws 无关。

实际抛出类型 默认事务结果
RuntimeException 及其子类 回滚
Error 及其子类 回滚
checked exception 提交,前提是事务未被其他机制标记为 rollback-only

因此,IllegalStateException 默认会回滚;直接继承 Exception 而不继承 RuntimeException 的异常,默认不会仅因为异常本身而触发回滚。

用完整实验验证结果

下面只保留一个主实验:第一次事务更新后抛出运行时异常,第二次事务更新后抛出 checked exception。项目只需要 pom.xml 和一个 Java 源文件,不依赖已有仓库代码。

pom.xml:

xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.3.5</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>rollback-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

该配置引入 JdbcTemplate、Spring JDBC 事务管理能力和内存数据库 H2。下面通过实际运行应用验证配置和事务行为。

创建 src/main/java/com/example/tx/RollbackDemoApplication.java:

java
package com.example.tx;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@SpringBootApplication
public class RollbackDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(RollbackDemoApplication.class, args);
    }
}

@Component
class DemoRunner implements CommandLineRunner {
    private final JdbcTemplate jdbcTemplate;
    private final AccountService accountService;

    DemoRunner(JdbcTemplate jdbcTemplate, AccountService accountService) {
        this.jdbcTemplate = jdbcTemplate;
        this.accountService = accountService;
    }

    @Override
    public void run(String... args) {
        jdbcTemplate.execute("drop table if exists account");
        jdbcTemplate.execute("create table account (id bigint primary key, balance int not null)");
        jdbcTemplate.update("insert into account(id, balance) values (1, 0)");

        // 运行时异常穿过事务代理边界,默认触发回滚。
        try {
            accountService.runtimeFailure();
        } catch (IllegalStateException ignored) {
        }
        System.out.println("after runtimeFailure: balance=" + balance());

        // checked exception 穿过事务代理边界,但默认不会触发回滚。
        try {
            accountService.checkedFailure();
        } catch (Exception ignored) {
        }
        System.out.println("after checkedFailure: balance=" + balance());
    }

    private int balance() {
        return jdbcTemplate.queryForObject(
                "select balance from account where id = 1", Integer.class);
    }
}

@Repository
class AccountRepository {
    private final JdbcTemplate jdbcTemplate;

    AccountRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    void incrementBalance(int amount) {
        jdbcTemplate.update(
                "update account set balance = balance + ? where id = 1", amount);
    }
}

@Service
class AccountService {
    private final AccountRepository accountRepository;

    AccountService(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    @Transactional
    public void runtimeFailure() {
        accountRepository.incrementBalance(100);
        throw new IllegalStateException("runtime failure");
    }

    @Transactional
    public void checkedFailure() throws Exception {
        accountRepository.incrementBalance(100);
        throw new Exception("checked failure");
    }
}

在 pom.xml 所在目录执行:

bash
mvn -q spring-boot:run

预期输出

text
after runtimeFailure: balance=0
after checkedFailure: balance=100

忽略 Spring Boot 自身日志即可。第一次更新后抛出 IllegalStateException,异常传播到事务代理,事务回滚,因此余额仍为 0。第二次更新后抛出 checked exception,默认规则允许事务提交,因此余额变为 100;随后异常继续传播,并由 DemoRunner 捕获。

异常传播和代理边界

默认回滚判断发生在事务拦截器结束本次方法调用时。若事务方法内部捕获了运行时异常并正常返回,又没有通过其他机制把事务标记为 rollback-only,事务代理看到的是一次正常完成的方法调用,通常会尝试提交事务。

@Transactional 出现在方法上也不代表事务一定建立。基于代理的常见场景中,同一个 Bean 内部使用 this 调用另一个事务方法可能绕过代理;此时相应方法上的事务拦截逻辑不会按预期执行。上面的实验由 DemoRunner 调用独立的 AccountService Bean,因此调用会经过 Spring 管理的事务代理。

checked exception 也可以显式回滚

checked exception 只是默认不触发回滚,并不是不能回滚。业务语义要求撤销事务时,可以使用 @Transactional(rollbackFor = Exception.class),更推荐指定实际需要回滚的业务异常类型,避免把所有 checked exception 都扩大为回滚条件。

判断一次事务最终提交还是回滚,可以按“事务是否建立 → 异常是否传播到代理 → 实际异常类型 → 是否存在自定义规则或 rollback-only 标记”的顺序检查。这样既能解释默认行为,也能快速定位异常被捕获或代理边界失效造成的偏差。

按自己的节奏,确认真正理解。

目录与阅读设置

记录一个想法

理解默认回滚规则

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通