Skip to lesson

Rollback rules for checked and unchecked exceptions

A stock change is saved, then the method throws and the customer sees an error. Did the stock change stay? The answer depends on one rule that many developers learn only after losing data.

The default: RuntimeException and Error roll back, checked exceptions commit

A rollback rule decides what Spring does when an exception leaves a @Transactional method: undo the work, or commit what was done before the exception.

Two methods take one copy of Clean Code out of stock and then throw. One throws an unchecked exception, the other a checked one. Watch which stock change survives.

Example 1 · DispatchService.java: an unchecked exception rolls back, a checked one commits

Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)

DispatchService.javaJava
// src/main/java/com/shoplite/lab/rollback/DispatchService.javapackage com.shoplite.lab.rollback;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
/** Each method takes one unit out of stock and then fails, so we can see what Spring does with the change. */@Servicepublic class DispatchService {
    private final ProductRepository products;
    public DispatchService(ProductRepository products) {        this.products = products;    }
    @Transactional    public void failUnchecked(int productId) {        takeOne(productId);        throw new IllegalStateException("Courier API returned 503");    }
    @Transactional    public void failChecked(int productId) throws CourierUnavailableException {        takeOne(productId);        throw new CourierUnavailableException("No courier serves pincode 682036 today");    }
    @Transactional(rollbackFor = CourierUnavailableException.class)    public void failCheckedWithRollbackFor(int productId) throws CourierUnavailableException {        takeOne(productId);        throw new CourierUnavailableException("No courier serves pincode 682036 today");    }
    @Transactional(noRollbackFor = SmsFailedException.class)    public void failSmsWithNoRollbackFor(int productId) {        takeOne(productId);        throw new SmsFailedException("SMS gateway timed out");    }
    private void takeOne(int productId) {        Product product = products.findById(productId).orElseThrow();        product.setStock(product.getStock() - 1);    }}
// src/main/java/com/shoplite/lab/rollback/CourierUnavailableException.javapackage com.shoplite.lab.rollback;
/** A checked exception: it extends Exception, not RuntimeException. */public class CourierUnavailableException extends Exception {
    public CourierUnavailableException(String message) {        super(message);    }}
// src/main/java/com/shoplite/lab/rollback/DefaultRulesDemo.javapackage com.shoplite.lab.rollback;
import org.springframework.stereotype.Component;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;
@Component("rollback-default")public class DefaultRulesDemo implements LabDemo {
    private static final int CLEAN_CODE = 9;
    private final DispatchService dispatch;    private final LabDb db;
    public DefaultRulesDemo(DispatchService dispatch, LabDb db) {        this.dispatch = dispatch;        this.db = db;    }
    @Override    public void run() {        System.out.println("Stock at start: " + db.stock(CLEAN_CODE));
        try {            dispatch.failUnchecked(CLEAN_CODE);        } catch (IllegalStateException e) {            System.out.println("1. unchecked:              " + e.getMessage() + " -> stock " + db.stock(CLEAN_CODE));        }        try {            dispatch.failChecked(CLEAN_CODE);        } catch (CourierUnavailableException e) {            System.out.println("2. checked:                " + e.getMessage() + " -> stock " + db.stock(CLEAN_CODE));        }    }}
Sample output (transaction log trimmed to the begin and commit or rollback lines)
$ java -jar target/tx-lab-0.1.0.jar --demo=rollback-default
Stock at start: 30
DEBUG o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [com.shoplite.lab.rollback.DispatchService.failUnchecked]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction rollback
1. unchecked:              Courier API returned 503 -> stock 30
DEBUG o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [com.shoplite.lab.rollback.DispatchService.failChecked]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction commit
2. checked:                No courier serves pincode 682036 today -> stock 29

What this code does

  • Both methods take one copy of Clean Code out of stock and then throw. For IllegalStateException the log says Initiating transaction rollback, and the stock is still 30.
  • For the checked CourierUnavailableException the log says Initiating transaction commit: the stock dropped to 29 although the method failed.

By default Spring rolls back when an unchecked exception leaves the method (a RuntimeException, one of its subclasses, or an Error). For a checked exception, which extends Exception and must be declared with throws, it commits everything done before the throw. The rule comes from older Java EE servers, which treated a checked exception as an expected business outcome the caller would handle.

In practice, a stock change can be saved although the method failed. Section 15 showed this with JdbcClient; with JPA the commit flushes the dirty entity, so the half-done change reaches MySQL.

Predict the output

Commit or roll back?

Each method takes one copy out of stock, then throws.

Round 1 of 3

Is the stock change saved?

@Transactional
public void dispatch() {
takeOneCopy();
throw new IllegalStateException("no courier");
}

rollbackFor and noRollbackFor

rollbackFor makes a checked exception roll back, and noRollbackFor does the opposite. The demo calls the last two methods of DispatchService and reads the transaction log.

Example 2 · rollbackFor and noRollbackFor in the log

Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)

RollbackAttributesDemo.javaJava
// src/main/java/com/shoplite/lab/rollback/RollbackAttributesDemo.javapackage com.shoplite.lab.rollback;
import org.springframework.stereotype.Component;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;
@Component("rollback-attributes")public class RollbackAttributesDemo implements LabDemo {
    private static final int CLEAN_CODE = 9;   // 30 in stock
    private final DispatchService dispatch;    private final LabDb db;
    public RollbackAttributesDemo(DispatchService dispatch, LabDb db) {        this.dispatch = dispatch;        this.db = db;    }
    @Override    public void run() {        System.out.println("Stock at start: " + db.stock(CLEAN_CODE));
        try {            dispatch.failCheckedWithRollbackFor(CLEAN_CODE);        } catch (CourierUnavailableException e) {            System.out.println("3. checked + rollbackFor:     " + e.getMessage() + " -> stock " + db.stock(CLEAN_CODE));        }        try {            dispatch.failSmsWithNoRollbackFor(CLEAN_CODE);        } catch (SmsFailedException e) {            System.out.println("4. unchecked + noRollbackFor: " + e.getMessage() + " -> stock " + db.stock(CLEAN_CODE));        }    }}
// src/main/java/com/shoplite/lab/rollback/SmsFailedException.javapackage com.shoplite.lab.rollback;
/** Unchecked: the SMS gateway did not accept the message. */public class SmsFailedException extends RuntimeException {
    public SmsFailedException(String message) {        super(message);    }}
Sample output (transaction log trimmed to the begin and commit or rollback lines)
$ java -jar target/tx-lab-0.1.0.jar --demo=rollback-attributes
Stock at start: 30
DEBUG o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [com.shoplite.lab.rollback.DispatchService.failCheckedWithRollbackFor]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,-com.shoplite.lab.rollback.CourierUnavailableException
DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction rollback
3. checked + rollbackFor:     No courier serves pincode 682036 today -> stock 30
DEBUG o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [com.shoplite.lab.rollback.DispatchService.failSmsWithNoRollbackFor]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,+com.shoplite.lab.rollback.SmsFailedException
DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction commit
4. unchecked + noRollbackFor: SMS gateway timed out -> stock 29

What this code does

  • The demo calls the last two methods of DispatchService from Example 1. With rollbackFor, the checked exception rolled back (stock 30); the log names the rule as -...CourierUnavailableException.
  • With noRollbackFor, the unchecked SmsFailedException still reached the caller, yet the transaction committed (stock 29); the log shows +...SmsFailedException.

@Transactional(rollbackFor = CourierUnavailableException.class) adds a type that must roll back. noRollbackFor names an exception that still leaves the method but lets the transaction commit. Both cover subclasses, and the log shows them as -CourierUnavailableException (roll back) and +SmsFailedException (commit).

Use noRollbackFor rarely and on purpose, for a side effect that must not undo the main work. The exception still reaches the caller, who must read it as "saved, but something else failed".

Catching inside: "Transaction silently rolled back because it has been marked as rollback-only"

A rollback-only transaction is a shared transaction that has been marked so that it can only roll back. Spring marks it when an inner @Transactional call that joined it throws.

An inner method joins the buyer's transaction and throws, and the outer method catches the exception and carries on. Run it and see what the caller gets.

Example 3 · PurchaseService.java: catching an inner failure gives UnexpectedRollbackException

Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)

LoyaltyService.javaJava
// src/main/java/com/shoplite/lab/rollback/LoyaltyService.javapackage com.shoplite.lab.rollback;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
@Servicepublic class LoyaltyService {
    @Transactional    public void addPoints(int customerId, int points) {        if (customerId == 2) {            throw new IllegalStateException("Loyalty card of customer 2 is blocked");        }        System.out.println("Added " + points + " points for customer " + customerId);    }}
// src/main/java/com/shoplite/lab/rollback/PurchaseService.javapackage com.shoplite.lab.rollback;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Servicepublic class PurchaseService {
    private final ProductRepository products;    private final LoyaltyService loyalty;
    public PurchaseService(ProductRepository products, LoyaltyService loyalty) {        this.products = products;        this.loyalty = loyalty;    }
    @Transactional    public void buy(int customerId, int productId) {        Product product = products.findById(productId).orElseThrow();        product.setStock(product.getStock() - 1);        try {            loyalty.addPoints(customerId, 50);        } catch (IllegalStateException e) {            System.out.println("Ignoring: " + e.getMessage());        }        System.out.println("buy() finished normally");    }}
// src/main/java/com/shoplite/lab/rollback/RollbackOnlyDemo.javapackage com.shoplite.lab.rollback;
import org.springframework.stereotype.Component;import org.springframework.transaction.UnexpectedRollbackException;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;
@Component("rollback-only")public class RollbackOnlyDemo implements LabDemo {
    private final PurchaseService purchases;    private final LabDb db;
    public RollbackOnlyDemo(PurchaseService purchases, LabDb db) {        this.purchases = purchases;        this.db = db;    }
    @Override    public void run() {        try {            purchases.buy(2, 9);        } catch (UnexpectedRollbackException e) {            System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());        }        System.out.println("Clean Code stock: " + db.stock(9));    }}
Sample output
$ java -jar target/tx-lab-0.1.0.jar --demo=rollback-only
DEBUG o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [com.shoplite.lab.rollback.PurchaseService.buy]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
DEBUG o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(892034876<open>)] for JPA transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@2f229f60]
DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(892034876<open>)] for JPA transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(892034876<open>)] for JPA transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Participating transaction failed - marking existing transaction as rollback-only
DEBUG o.s.orm.jpa.JpaTransactionManager : Setting JPA transaction on EntityManager [SessionImpl(892034876<open>)] rollback-only
Ignoring: Loyalty card of customer 2 is blocked
buy() finished normally
DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction commit
DEBUG o.s.orm.jpa.JpaTransactionManager : Committing JPA transaction on EntityManager [SessionImpl(892034876<open>)]
DEBUG o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager after transaction
UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only
Clean Code stock: 30

What this code does

  • addPoints joined the buy transaction and threw, so its proxy logged Participating transaction failed - marking existing transaction as rollback-only.
  • buy caught the exception and finished normally, so its proxy tried to commit, found the mark, rolled back and threw UnexpectedRollbackException. The sale is gone: stock is still 30.

The inner proxy cannot roll back alone, because the transaction is shared. It marks the whole transaction rollback-only and lets the exception go on. When the outer method returns normally, its proxy finds the mark, rolls back and throws UnexpectedRollbackException: "Transaction silently rolled back because it has been marked as rollback-only". The caller who expected success gets an error, and the work is gone.

Only an exception that crossed a transactional proxy causes this; a try/catch around plain code in the same method marks nothing. Fix it by letting the whole operation fail, by checking the condition first instead of throwing for a normal case, or by giving the optional part its own transaction (REQUIRES_NEW, in the Propagation lesson).

Find the bug

Find the line that causes it

Each method ends with a rolled-back transaction. Tap the wrong line.

addPoints is a @Transactional method of another bean and can throw.

Round 1 of 2

Why ShopLite exceptions are unchecked

Every ShopLite business exception extends ShopLiteException, which extends RuntimeException, so a thrown business error rolls back with no extra settings.

ShopLiteException.javaJava
public abstract class ShopLiteException extends RuntimeException {   // unchecked: rolls back    protected ShopLiteException(String message) {        super(message);    }}
public abstract class ConflictException extends ShopLiteException { ... }        // 409public class OutOfStockException extends ConflictException { ... }              // 409 out-of-stockpublic class InvalidStateException extends ConflictException { ... }            // 409 invalid-state

No throws clause is needed in any layer, and the one GlobalExceptionHandler from Section 15 still turns each exception into a ProblemDetail. For new code:

  • A new business exception extends one of these classes, never Exception directly.
  • If a library throws a checked exception (a payment SDK, a file API), catch it in the service and rethrow a ShopLite exception, or add rollbackFor.
  • Never catch an exception just to log it and go on inside a transaction; let it reach the handler.

A test that checks stock is unchanged after a failure

A rollback test calls the service with data that must fail, then reads the database to prove nothing changed. The test below records the stock first and compares relative numbers.

Example 4 · OrderPlacementServiceTest.java: a failed order changes nothing

Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// src/test/java/com/shoplite/lab/placement/OrderPlacementServiceTest.javapackage com.shoplite.lab.placement;
import static org.assertj.core.api.Assertions.assertThat;import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.List;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;
import com.shoplite.lab.LabDb;
// No @Transactional on this class: each place() call must commit or roll back for real@SpringBootTest(properties = "demo=none")class OrderPlacementServiceTest {
    private static final int CLEAN_CODE = 9;    private static final int IPHONE = 3;
    @Autowired    private OrderPlacementService placement;
    @Autowired    private LabDb db;
    @Test    void failedOrderLeavesStockAndOrdersUnchanged() {        int cleanCodeBefore = db.stock(CLEAN_CODE);        int iphoneBefore = db.stock(IPHONE);        long ordersBefore = db.orders();
        // Clean Code is fine, but nobody can buy one more iPhone than is in stock        List<OrderLine> lines = List.of(new OrderLine(CLEAN_CODE, 1), new OrderLine(IPHONE, iphoneBefore + 1));
        assertThatThrownBy(() -> placement.place(2, 3, lines))                .isInstanceOf(OutOfStockException.class)                .hasMessageContaining("iPhone 15 128GB");
        assertThat(db.stock(CLEAN_CODE)).isEqualTo(cleanCodeBefore);        assertThat(db.stock(IPHONE)).isEqualTo(iphoneBefore);        assertThat(db.orders()).isEqualTo(ordersBefore);    }
    @Test    void successfulOrderTakesStockAndSavesTheOrder() {        int cleanCodeBefore = db.stock(CLEAN_CODE);        long ordersBefore = db.orders();
        placement.place(1, 1, List.of(new OrderLine(CLEAN_CODE, 2)));
        assertThat(db.stock(CLEAN_CODE)).isEqualTo(cleanCodeBefore - 2);        assertThat(db.orders()).isEqualTo(ordersBefore + 1);    }}
Sample output
$ ./mvnw test -Dtest=OrderPlacementServiceTest
...
[INFO] Running com.shoplite.lab.placement.OrderPlacementServiceTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 34.31 s -- in com.shoplite.lab.placement.OrderPlacementServiceTest
[INFO] 
[INFO] Results:
[INFO] 
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] 
[INFO] BUILD SUCCESS

What this code does

  • The first test asks for one more iPhone than exists, checks the exception and its message, then reads Clean Code's stock, the iPhone's stock and the order count with plain SQL: all unchanged.
  • LabDb reads with JdbcClient outside any test transaction, so it sees only what was committed. The second test proves the happy path really commits.
  • properties = "demo=none" stops the lab's demo runner during tests. In ShopLite the same kind of test lives in the order-cancellation project.

Read the rows with plain SQL (or a fresh repository call) after the service returned, so you see what MySQL really holds. Comparing relative numbers keeps the test passing on any copy of the seed data.

Do not put @Transactional on such a test class. Spring would wrap each test in its own transaction and roll it back at the end, the service call would join that transaction, and you would never test the real commit or rollback.

Next step

Check your understanding

12 quick questions