Back to Rollback Rules & Pitfalls
Q7Question 7 of 5

When does Spring roll back a transaction

Answer: Spring rolls back a @Transactional method only for unchecked exceptions (RuntimeException, Error) by default; checked exceptions cause a commit unless you explicitly set rollbackFor.

Key Concepts
  • By default, Spring rolls back the transaction only for unchecked exceptions (RuntimeException and its subclasses) and Errors.
  • Checked exceptions (Exception subclasses that are not RuntimeException) cause a commit by default, not a rollback.
  • Use rollbackFor to override the default: @Transactional(rollbackFor = Exception.class) rolls back for all exceptions including checked ones.
  • Use noRollbackFor to prevent rollback for specific runtime exceptions: @Transactional(noRollbackFor = ItemNotFoundException.class).
  • If you catch an exception inside the @Transactional method and do not re-throw it, Spring never sees the exception and always commits.
  • This is the second most common @Transactional pitfall after self-invocation: developers throw a checked exception expecting a rollback, but the transaction commits.

Definition

Spring rolls back a @Transactional method only for unchecked exceptions (RuntimeException, Error) by default; checked exceptions cause a commit unless you explicitly set rollbackFor.
  • Unchecked exception is any exception extending RuntimeException; Spring rolls back the transaction automatically when one is thrown from a @Transactional method.
  • Checked exception is any exception extending Exception but not RuntimeException; by default, Spring commits the transaction when a checked exception is thrown.
  • rollbackFor is the attribute on @Transactional that tells Spring to roll back for specific exception types, overriding the default commit behavior for checked exceptions.
  • noRollbackFor is the attribute that tells Spring to commit even when a specific runtime exception is thrown, overriding the default rollback behavior.
  • Error (like OutOfMemoryError, StackOverflowError) triggers a rollback by default, same as RuntimeException.
  • Swallowed exception is when you catch an exception inside the @Transactional method and do not re-throw; Spring never sees it and commits the transaction regardless of what happened.

Think of the National Bank of India branch manager processing a loan application. If a serious error occurs, like the applicant's identity is fraudulent (RuntimeException), the manager tears up the paperwork and reverses all entries (rollback). But if a minor issue comes up, like the applicant forgot to sign one form (checked exception), the manager assumes the application is still valid and files it (commit). To change this behavior, the manager needs an explicit instruction (rollbackFor) saying: tear up the application for missing signatures too.

Understanding the Concepts

What is the default rollback behavior?

  • Spring follows a simple rule by default:
  • RuntimeException or Error thrown from a @Transactional method: transaction rolls back.
  • Checked Exception thrown from a @Transactional method: transaction commits.
  • No exception: transaction commits.

This default comes from the EJB specification that Spring originally mirrored. The reasoning was that checked exceptions represent recoverable business conditions (like "insufficient balance"), while unchecked exceptions represent programming errors or system failures.

JAVA
package com.bank.service;

import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class DefaultRollbackDemo {

    private final AccountRepository accountRepository;

    public DefaultRollbackDemo(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    @Transactional
    public void transferWithRuntimeException(String from, String to, BigDecimal amount) {
        Account sender = accountRepository.findByAccountNumber(from).orElseThrow();
        sender.setBalance(sender.getBalance().subtract(amount));
        accountRepository.save(sender);

        // RuntimeException -> ROLLBACK (debit is undone)
        throw new RuntimeException("System failure during transfer");
    }

    @Transactional
    public void transferWithCheckedException(String from, String to, BigDecimal amount)
            throws Exception {
        Account sender = accountRepository.findByAccountNumber(from).orElseThrow();
        sender.setBalance(sender.getBalance().subtract(amount));
        accountRepository.save(sender);

        // Checked Exception -> COMMIT (debit is permanent!)
        throw new Exception("Business validation failed");
    }
}
JAVA
package com.bank;

import com.bank.repository.AccountRepository;
import com.bank.service.DefaultRollbackDemo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component
public class RollbackDemoRunner implements CommandLineRunner {

    private final DefaultRollbackDemo service;
    private final AccountRepository repo;

    public RollbackDemoRunner(DefaultRollbackDemo service, AccountRepository repo) {
        this.service = service;
        this.repo = repo;
    }

    @Override
    public void run(String... args) {
        // Test 1: RuntimeException -> rollback
        try {
            service.transferWithRuntimeException("SAV2001", "SAV2002", new BigDecimal("10000"));
        } catch (RuntimeException e) {
            System.out.println("Caught: " + e.getMessage());
        }
        var balance1 = repo.findByAccountNumber("SAV2001").orElseThrow().getBalance();
        System.out.println("After RuntimeException: SAV2001 balance = " + balance1);
        System.out.println("  (Rolled back: balance unchanged)");

        // Test 2: Checked exception -> commit
        try {
            service.transferWithCheckedException("SAV2001", "SAV2002", new BigDecimal("10000"));
        } catch (Exception e) {
            System.out.println("Caught: " + e.getMessage());
        }
        var balance2 = repo.findByAccountNumber("SAV2001").orElseThrow().getBalance();
        System.out.println("After Checked Exception: SAV2001 balance = " + balance2);
        System.out.println("  (COMMITTED: balance decreased even though exception was thrown!)");
    }
}
TEXT
Expected output:
Caught: System failure during transfer
After RuntimeException: SAV2001 balance = 50000
  (Rolled back: balance unchanged)
Caught: Business validation failed
After Checked Exception: SAV2001 balance = 40000
  (COMMITTED: balance decreased even though exception was thrown!)

What is rollbackFor and how do you use it?

The rollbackFor attribute on @Transactional tells Spring to roll back the transaction for specific exception types, including checked exceptions. The most common usage is rollbackFor = Exception.class, which rolls back for any exception.

JAVA
package com.bank.service;

import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class RollbackForDemo {

    private final AccountRepository accountRepository;

    public RollbackForDemo(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    // CORRECT: rollbackFor = Exception.class rolls back for ALL exceptions
    @Transactional(rollbackFor = Exception.class)
    public void transferWithRollbackFor(String from, String to, BigDecimal amount)
            throws Exception {
        Account sender = accountRepository.findByAccountNumber(from).orElseThrow();
        sender.setBalance(sender.getBalance().subtract(amount));
        accountRepository.save(sender);

        // Now checked exceptions ALSO cause rollback
        throw new Exception("Business validation failed");
    }
}
JAVA
package com.bank;

import com.bank.repository.AccountRepository;
import com.bank.service.RollbackForDemo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component
public class RollbackForRunner implements CommandLineRunner {

    private final RollbackForDemo service;
    private final AccountRepository repo;

    public RollbackForRunner(RollbackForDemo service, AccountRepository repo) {
        this.service = service;
        this.repo = repo;
    }

    @Override
    public void run(String... args) {
        try {
            service.transferWithRollbackFor("SAV2001", "SAV2002", new BigDecimal("10000"));
        } catch (Exception e) {
            System.out.println("Caught: " + e.getMessage());
        }
        var balance = repo.findByAccountNumber("SAV2001").orElseThrow().getBalance();
        System.out.println("After rollbackFor: SAV2001 balance = " + balance);
        System.out.println("  (Rolled back: checked exception now triggers rollback)");
    }
}
TEXT
Expected output:
Caught: Business validation failed
After rollbackFor: SAV2001 balance = 50000
  (Rolled back: checked exception now triggers rollback)

What is noRollbackFor?

noRollbackFor is the opposite of rollbackFor. It tells Spring to commit the transaction even when a specific runtime exception is thrown. This is useful when a runtime exception represents a non-critical business condition that should not undo the work.

JAVA
package com.bank.exception;

public class AccountNotFoundException extends RuntimeException {
    public AccountNotFoundException(String accountNumber) {
        super("Account not found: " + accountNumber);
    }
}
JAVA
package com.bank.service;

import com.bank.exception.AccountNotFoundException;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class NoRollbackForDemo {

    private final AccountRepository accountRepository;

    public NoRollbackForDemo(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    // Commit even if AccountNotFoundException is thrown
    @Transactional(noRollbackFor = AccountNotFoundException.class)
    public void processPayments() {
        // First payment succeeds and should stay committed
        Account priya = accountRepository.findByAccountNumber("SAV2001").orElseThrow();
        priya.setBalance(priya.getBalance().add(new BigDecimal("5000")));
        accountRepository.save(priya);
        System.out.println("Payment 1: credited 5000 to SAV2001");

        // Second payment fails, but first payment should still be committed
        throw new AccountNotFoundException("SAV9999");
    }
}
TEXT
Expected output:
Payment 1: credited 5000 to SAV2001
Exception: Account not found: SAV9999
SAV2001 balance = 55000 (committed despite exception)

What happens when you catch the exception inside the method?

If you catch an exception inside the @Transactional method and do not re-throw it, Spring never sees the exception. The TransactionInterceptor only checks whether the method threw an exception. If the method returns normally (even after catching an internal exception), Spring commits.

JAVA
package com.bank.service;

import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class SwallowedExceptionDemo {

    private final AccountRepository accountRepository;

    public SwallowedExceptionDemo(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    @Transactional
    public void processWithSwallowedException() {
        Account sender = accountRepository.findByAccountNumber("SAV2001").orElseThrow();
        sender.setBalance(sender.getBalance().subtract(new BigDecimal("10000")));
        accountRepository.save(sender);

        try {
            // This exception is caught and not re-thrown
            riskyOperation();
        } catch (RuntimeException e) {
            System.out.println("Caught exception: " + e.getMessage());
            System.out.println("NOT re-throwing. Spring will COMMIT.");
            // FIX: throw e; // Re-throw to trigger rollback
        }
        // Method returns normally -> Spring COMMITS
    }

    private void riskyOperation() {
        throw new RuntimeException("Something went wrong");
    }
}
TEXT
Expected output:
Caught exception: Something went wrong
NOT re-throwing. Spring will COMMIT.
SAV2001 balance = 40000 (debit was committed, no rollback)

What is a complete banking project demonstrating rollback rules?

Project structure

DIAGRAM
rollback-rules-demo/
├── pom.xml
└── src/
    ├── main/
    │   ├── java/
    │   │   └── com/
    │   │       └── bank/
    │   │           ├── RollbackApp.java
    │   │           ├── exception/
    │   │           │   ├── InsufficientBalanceException.java
    │   │           │   └── FraudDetectedException.java
    │   │           ├── model/
    │   │           │   └── Account.java
    │   │           ├── repository/
    │   │           │   └── AccountRepository.java
    │   │           └── service/
    │   │               └── PaymentService.java
    │   └── resources/
    │       └── application.properties
    └── test/
        └── java/
            └── com/
                └── bank/
                    └── service/
                        └── PaymentServiceRollbackTest.java

pom.xml

XML
<?xml version="1.0" encoding="UTF-8"?syn-kw">>
syn-kw"><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
         http://maven.apache.org/xsd/maven-4.0.0.xsd"syn-kw">>
    syn-kw"><modelVersionsyn-kw">>4.0.0syn-kw"></modelVersionsyn-kw">>

    syn-kw"><parentsyn-kw">>
        syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
        syn-kw"><artifactIdsyn-kw">>spring-boot-starter-parentsyn-kw"></artifactIdsyn-kw">>
        syn-kw"><versionsyn-kw">>3.4.7syn-kw"></versionsyn-kw">>
    syn-kw"></parentsyn-kw">>

    syn-kw"><groupIdsyn-kw">>com.banksyn-kw"></groupIdsyn-kw">>
    syn-kw"><artifactIdsyn-kw">>rollback-rules-demosyn-kw"></artifactIdsyn-kw">>
    syn-kw"><versionsyn-kw">>1.0.0syn-kw"></versionsyn-kw">>

    syn-kw"><propertiessyn-kw">>
        syn-kw"><java.versionsyn-kw">>25syn-kw"></java.versionsyn-kw">>
    syn-kw"></propertiessyn-kw">>

    syn-kw"><dependenciessyn-kw">>
        syn-kw"><dependencysyn-kw">>
            syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
            syn-kw"><artifactIdsyn-kw">>spring-boot-starter-data-jpasyn-kw"></artifactIdsyn-kw">>
        syn-kw"></dependencysyn-kw">>
        syn-kw"><dependencysyn-kw">>
            syn-kw"><groupIdsyn-kw">>com.h2databasesyn-kw"></groupIdsyn-kw">>
            syn-kw"><artifactIdsyn-kw">>h2syn-kw"></artifactIdsyn-kw">>
            syn-kw"><scopesyn-kw">>runtimesyn-kw"></scopesyn-kw">>
        syn-kw"></dependencysyn-kw">>
        syn-kw"><dependencysyn-kw">>
            syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
            syn-kw"><artifactIdsyn-kw">>spring-boot-starter-testsyn-kw"></artifactIdsyn-kw">>
            syn-kw"><scopesyn-kw">>testsyn-kw"></scopesyn-kw">>
        syn-kw"></dependencysyn-kw">>
    syn-kw"></dependenciessyn-kw">>
syn-kw"></projectsyn-kw">>

Custom exceptions using sealed interface (Java 25)

JAVA
package com.bank.exception;

public sealed interface PaymentException permits
    InsufficientBalanceException, FraudDetectedException {}
JAVA
package com.bank.exception;

// Checked exception: balance too low
public final class InsufficientBalanceException extends Exception implements PaymentException {
    public InsufficientBalanceException(String accountNumber, java.math.BigDecimal balance, java.math.BigDecimal required) {
        super("Account " + accountNumber + ": balance " + balance + " < required " + required);
    }
}
JAVA
package com.bank.exception;

// Unchecked exception: fraud detected
public final class FraudDetectedException extends RuntimeException implements PaymentException {
    public FraudDetectedException(String accountNumber) {
        super("Fraud detected on account: " + accountNumber);
    }
}

PaymentService.java

JAVA
package com.bank.service;

import com.bank.exception.FraudDetectedException;
import com.bank.exception.InsufficientBalanceException;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class PaymentService {

    private final AccountRepository accountRepository;

    public PaymentService(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    // DEFAULT: rolls back for RuntimeException only
    @Transactional
    public void payWithDefault(String accountNumber, BigDecimal amount)
            throws InsufficientBalanceException {
        Account account = accountRepository.findByAccountNumber(accountNumber).orElseThrow();
        if (account.getBalance().compareTo(amount) < 0) {
            // CHECKED exception -> NO ROLLBACK by default
            throw new InsufficientBalanceException(accountNumber, account.getBalance(), amount);
        }
        account.setBalance(account.getBalance().subtract(amount));
        accountRepository.save(account);
    }

    // FIXED: rollbackFor includes checked exceptions
    @Transactional(rollbackFor = Exception.class)
    public void payWithRollbackFor(String accountNumber, BigDecimal amount)
            throws InsufficientBalanceException {
        Account account = accountRepository.findByAccountNumber(accountNumber).orElseThrow();
        account.setBalance(account.getBalance().subtract(amount));
        accountRepository.save(account);

        if (amount.compareTo(new BigDecimal("500000")) > 0) {
            throw new InsufficientBalanceException(accountNumber, account.getBalance(), amount);
        }
    }

    // RuntimeException: always rolls back by default
    @Transactional
    public void payWithFraudCheck(String accountNumber, BigDecimal amount) {
        Account account = accountRepository.findByAccountNumber(accountNumber).orElseThrow();
        account.setBalance(account.getBalance().subtract(amount));
        accountRepository.save(account);

        // UNCHECKED exception -> ROLLBACK by default
        throw new FraudDetectedException(accountNumber);
    }
}

PaymentServiceRollbackTest.java

JAVA
package com.bank.service;

import com.bank.exception.FraudDetectedException;
import com.bank.exception.InsufficientBalanceException;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.math.BigDecimal;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

@SpringBootTest
class PaymentServiceRollbackTest {

    @Autowired private PaymentService paymentService;
    @Autowired private AccountRepository accountRepository;

    @BeforeEach
    void setUp() {
        accountRepository.deleteAll();
        accountRepository.save(new Account("SAV2001", "Priya Sharma", new BigDecimal("50000"), "ACTIVE"));
    }

    @Test
    void checkedExceptionWithoutRollbackFor_commits() {
        assertThrows(InsufficientBalanceException.class, () ->
            paymentService.payWithDefault("SAV2001", new BigDecimal("100000")));

        var balance = accountRepository.findByAccountNumber("SAV2001").orElseThrow().getBalance();
        assertEquals(new BigDecimal("50000"), balance);
        System.out.println("Test 1: checked exception without rollbackFor");
        System.out.println("  Balance: " + balance + " (no debit happened, validation caught it)");
    }

    @Test
    void checkedExceptionWithRollbackFor_rollsBack() {
        assertThrows(InsufficientBalanceException.class, () ->
            paymentService.payWithRollbackFor("SAV2001", new BigDecimal("600000")));

        var balance = accountRepository.findByAccountNumber("SAV2001").orElseThrow().getBalance();
        assertEquals(new BigDecimal("50000"), balance);
        System.out.println("Test 2: checked exception WITH rollbackFor = Exception.class");
        System.out.println("  Balance: " + balance + " (rolled back!)");
    }

    @Test
    void runtimeException_rollsBackByDefault() {
        assertThrows(FraudDetectedException.class, () ->
            paymentService.payWithFraudCheck("SAV2001", new BigDecimal("10000")));

        var balance = accountRepository.findByAccountNumber("SAV2001").orElseThrow().getBalance();
        assertEquals(new BigDecimal("50000"), balance);
        System.out.println("Test 3: RuntimeException rolls back by default");
        System.out.println("  Balance: " + balance + " (rolled back!)");
    }
}
TEXT
Expected output:
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
Test 1: checked exception without rollbackFor
  Balance: 50000 (no debit happened, validation caught it)
Test 2: checked exception WITH rollbackFor = Exception.class
  Balance: 50000 (rolled back!)
Test 3: RuntimeException rolls back by default
  Balance: 50000 (rolled back!)
[INFO] BUILD SUCCESS

What are the rollback rules summarized?

Exception typeDefault behaviorWith rollbackFor = Exception.class
RuntimeExceptionRollbackRollback
Error (OOM, SOE)RollbackRollback
Checked ExceptionCommitRollback
Exception caught and not re-thrownCommitCommit
No exceptionCommitCommit
JAVA
package com.bank;

public class RollbackRulesSummary {
    public static void main(String[] args) {
        System.out.println("Spring @Transactional rollback rules:");
        System.out.println();
        System.out.println("RuntimeException         -> ROLLBACK (default)");
        System.out.println("Error                    -> ROLLBACK (default)");
        System.out.println("Checked Exception        -> COMMIT   (default!)");
        System.out.println("Caught, not re-thrown    -> COMMIT   (Spring never sees it)");
        System.out.println("No exception             -> COMMIT");
        System.out.println();
        System.out.println("Best practice for banking:");
        System.out.println("  Always use @Transactional(rollbackFor = Exception.class)");
        System.out.println("  This ensures ALL exceptions trigger rollback.");
        System.out.println("  In banking, a committed partial transaction means lost money.");
    }
}
TEXT
Expected output:
Spring @Transactional rollback rules:

RuntimeException         -> ROLLBACK (default)
Error                    -> ROLLBACK (default)
Checked Exception        -> COMMIT   (default!)
Caught, not re-thrown    -> COMMIT   (Spring never sees it)
No exception             -> COMMIT

Best practice for banking:
  Always use @Transactional(rollbackFor = Exception.class)
  This ensures ALL exceptions trigger rollback.
  In banking, a committed partial transaction means lost money.

What are common mistakes with rollback behavior?

Wrong: throwing checked exception expecting rollback

JAVA
package com.bank.service;

import com.bank.repository.AccountRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class WrongRollbackService {

    private final AccountRepository accountRepository;

    public WrongRollbackService(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    // WRONG: no rollbackFor, checked exception -> COMMIT
    @Transactional
    public void transfer(String from, String to, BigDecimal amount) throws Exception {
        var sender = accountRepository.findByAccountNumber(from).orElseThrow();
        sender.setBalance(sender.getBalance().subtract(amount));
        accountRepository.save(sender);

        // Checked exception -> Spring COMMITS the debit
        throw new Exception("External payment gateway failed");
    }
}
TEXT
Expected output:
Exception thrown: External payment gateway failed
SAV2001 balance: 40000 (COMMITTED, money lost!)
BUG: developer expected rollback, but Spring committed because Exception is checked.

Correct: add rollbackFor = Exception.class

JAVA
package com.bank.service;

import com.bank.repository.AccountRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class CorrectRollbackService {

    private final AccountRepository accountRepository;

    public CorrectRollbackService(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    // CORRECT: rollbackFor = Exception.class
    @Transactional(rollbackFor = Exception.class)
    public void transfer(String from, String to, BigDecimal amount) throws Exception {
        var sender = accountRepository.findByAccountNumber(from).orElseThrow();
        sender.setBalance(sender.getBalance().subtract(amount));
        accountRepository.save(sender);

        throw new Exception("External payment gateway failed");
    }
}
TEXT
Expected output:
Exception thrown: External payment gateway failed
SAV2001 balance: 50000 (ROLLED BACK, money safe!)

What should a senior or principal engineer know?

At the senior level, you should enforce a team coding standard: always use @Transactional(rollbackFor = Exception.class) in any service that handles money. The default commit-on-checked-exception behavior is a historical artifact from EJB and is almost never what you want in a banking application.

At the principal level, think about:

  • Global default override: create a custom meta-annotation that sets rollbackFor = Exception.class by default, so developers do not need to remember it on every method.
  • Transaction event listeners: use @TransactionalEventListener to execute side effects (sending emails, publishing events) only after the transaction commits. This prevents sending a "transfer successful" email when the transaction rolls back.
  • Programmatic rollback: when you need conditional rollback inside a method, use TransactionAspectSupport.currentTransactionStatus().setRollbackOnly() instead of throwing an exception.
  • Read-only transactions: @Transactional(readOnly = true) provides a hint to the database and Hibernate to optimize for reads. Hibernate disables dirty checking, which improves performance.
JAVA
package com.bank.config;

import org.springframework.transaction.annotation.Transactional;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

// Custom meta-annotation for the National Bank of India
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional(rollbackFor = Exception.class)
public @interface BankTransactional {
}
JAVA
package com.bank.service;

import com.bank.config.BankTransactional;
import com.bank.repository.AccountRepository;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class MetaAnnotationService {

    private final AccountRepository accountRepository;

    public MetaAnnotationService(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    // Uses custom meta-annotation: rollbackFor = Exception.class is automatic
    @BankTransactional
    public void secureTransfer(String from, String to, BigDecimal amount) throws Exception {
        var sender = accountRepository.findByAccountNumber(from).orElseThrow();
        sender.setBalance(sender.getBalance().subtract(amount));
        accountRepository.save(sender);

        throw new Exception("Gateway timeout");
        // ROLLS BACK because @BankTransactional includes rollbackFor = Exception.class
    }
}
TEXT
Expected output:
Exception: Gateway timeout
SAV2001 balance: 50000 (rolled back via @BankTransactional meta-annotation)

What are common interview follow-up questions?

  • Does @Transactional roll back for Throwable? (By default, no. Only RuntimeException and Error trigger rollback. Throwable itself is checked. Use rollbackFor = Throwable.class if you need it.)
  • What happens with nested exceptions wrapped in another exception? (Spring checks the thrown exception, not the cause. If you catch a RuntimeException and wrap it in a checked Exception, Spring sees the checked Exception and commits.)
  • Can you use multiple rollbackFor values? (Yes. Use rollbackFor = {IOException.class, TimeoutException.class} to specify multiple checked exceptions.)
  • What is the difference between rollbackFor and rollbackForClassName? (rollbackFor takes Class objects. rollbackForClassName takes String names, useful when you cannot import the exception class.)
  • Does setRollbackOnly() throw an exception? (No. It marks the transaction for rollback without throwing. The method can continue, but the transaction will roll back when it completes.)
  • What happens if a @Transactional(readOnly = true) method writes to the database? (It depends on the database and JPA provider. Some databases enforce read-only at the connection level. Hibernate will not flush dirty entities, so writes may be silently ignored.)

Visual Overview

DIAGRAM
 Spring Transaction Rollback Decision Tree
 ============================================

 ┌────────────────────────────┐
 │ @Transactional method exits │
 └──────────┬─────────────────┘
            │
     ┌──────┴──────┐
     │             │
  Normal?      Exception thrown?
     │             │
     ▼             ▼
 ┌────────┐   ┌────────────────────┐
 │ COMMIT │   │ What type?         │
 └────────┘   └────────┬───────────┘
                       │
           ┌───────────┼───────────┐
           │           │           │
      RuntimeException Error    Checked
      (unchecked)               Exception
           │           │           │
           ▼           ▼           ▼
      ┌──────────┐ ┌──────────┐ ┌──────────┐
      │ ROLLBACK │ │ ROLLBACK │ │ COMMIT   │
      │ (default)│ │ (default)│ │ (default)│
      └──────────┘ └──────────┘ └──────┬───┘
                                       │
                                  rollbackFor
                                  specified?
                                       │
                                  ┌────┴────┐
                                  │         │
                                 Yes        No
                                  │         │
                                  ▼         ▼
                             ┌──────────┐ ┌──────────┐
                             │ ROLLBACK │ │ COMMIT   │
                             └──────────┘ └──────────┘

Key Takeaway

Spring's default rollback rule catches most developers by surprise: only unchecked exceptions (RuntimeException and Error) cause a rollback. Checked exceptions cause a commit. This means if your payment service throws a checked InsufficientBalanceException after debiting the sender, Spring commits the debit and the money is gone. This behavior comes from the EJB specification, where checked exceptions were meant to represent recoverable business conditions.

In banking applications, this default is dangerous. Any exception during a financial transaction should roll back the entire operation. The fix is straightforward: use @Transactional(rollbackFor = Exception.class) on every transactional method, or create a custom @BankTransactional meta-annotation that includes this setting. This ensures that both checked and unchecked exceptions trigger a rollback.

The second trap is swallowing exceptions. If you catch a RuntimeException inside a @Transactional method and do not re-throw it, Spring sees a normal method return and commits. The TransactionInterceptor only checks whether the method threw an exception to the proxy. If the exception never reaches the proxy, the rollback rule never evaluates.

In our National Bank of India rollback-rules-demo, we created three test scenarios: a checked exception without rollbackFor (committed, money lost), the same checked exception with rollbackFor = Exception.class (rolled back, money safe), and a RuntimeException (rolled back by default). The tests verified each behavior by checking the account balance after the exception.

At the principal level, enforce rollbackFor = Exception.class as a team standard, use @TransactionalEventListener for side effects that should only happen after a successful commit, and consider programmatic rollback with setRollbackOnly() for conditional cases.

Remember one sentence: Spring commits on checked exceptions by default, so always use rollbackFor = Exception.class in banking applications to ensure every exception triggers a rollback.

---

Share
Use ← → arrow keys to navigate