Will These Spring @Transactional Methods Roll Back? Explore Four Scenarios

This article examines four Spring Boot @Transactional test cases using a MySQL InnoDB database to determine whether each method rolls back or commits when exceptions are thrown or caught, providing code examples and inviting readers to vote on the outcomes.

Programmer DD
Programmer DD
Programmer DD
Will These Spring @Transactional Methods Roll Back? Explore Four Scenarios

In a Spring Boot 2.x project using Spring Data JPA and MySQL 5.7 (InnoDB), a User entity is defined with a name field limited to 5 characters to trigger a validation exception.

The repository UserRepository handles CRUD operations. Four test methods annotated with @Transactional are examined to determine whether the transaction is rolled back under different exception handling scenarios.

Test 1

@Transactional
public void test1() {
    userRepository.save(new User("AAA", 10));
    throw new RuntimeException();
}

Because the RuntimeException is unchecked and not caught, the transaction is rolled back.

Test 2

@Transactional
public void test2() {
    userRepository.save(new User("AAA", 10));
    try {
        throw new RuntimeException();
    } catch (Exception e) {
        log.error("异常捕获:", e);
    }
}

Since the exception is caught and not re‑thrown, the transaction commits and the insert persists.

Test 3

@Transactional
public void test3() {
    userRepository.save(new User("AAA", 10));
    userRepository.save(new User("1234567890", 20));
}

The second save violates the @Size constraint, causing a validation exception that propagates out of the method, so the whole transaction is rolled back.

Test 4

@Transactional
public void test4() {
    userRepository.save(new User("AAA", 10));
    try {
        userRepository.save(new User("1234567890", 20));
    } catch (Exception e) {
        log.error("异常捕获:", e);
    }
}

Here the validation exception is caught, so the first insert remains committed while the second fails, resulting in a partial commit.

The article invites readers to vote on the expected outcomes and discuss their reasoning.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

transactionspringSpring Bootmysqlrollbackjpa
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.