Spring @Transactional: how it works and where it goes wrong

@Transactional looks like a simple switch, but Spring implements it with a proxy, a transaction manager and a value bound to the current thread. Most transaction bugs come from one of those three. This page explains each part, then runs every important rule and trap against a real database, from checked exceptions that commit to calls that skip the transaction entirely.

Contents

How Spring runs a method in a transaction

A database transaction groups several statements so that they take effect together or not at all. In plain JDBC you do this by hand: turn off auto-commit on a connection, run the statements, then call commit() or rollback(). Every method that writes to the database repeats the same pattern, and it is easy to get wrong.

@Transactional moves that pattern out of your code. Three pieces work together:

  • A proxy: when a bean has @Transactional methods, Spring does not hand out the bean itself. It creates a subclass (or an interface implementation) that wraps each annotated method, and injects that proxy wherever the bean is needed.
  • A transaction manager: before the method runs, the proxy asks the PlatformTransactionManager to begin a transaction, and afterwards to commit or roll back. DataSourceTransactionManager does this for JDBC, and JpaTransactionManager for JPA.
  • A thread-bound connection: the transaction manager binds the connection to the current thread with a ThreadLocal. JdbcTemplate, Spring Data repositories and JPA all look there first, which is how they take part in the transaction without being passed the connection.

Each piece has a limit, and most transaction bugs come from one of them. A call that does not go through the proxy gets no transaction. The transaction manager decides commit or rollback only from what the method throws. And work done on another thread does not see the thread-bound connection.

The annotation's attributes control what the proxy asks for:

@Transactional attributes and their defaults
AttributeDefaultWhat it controls
propagationREQUIREDWhether to join a transaction that is already running, start a new one, or run without one
isolationDEFAULT (the database's own level)How much the transaction sees of other transactions' changes
rollbackFor, noRollbackForRoll back on RuntimeException and Error onlyWhich exceptions cause a rollback
readOnlyfalseA hint that the transaction will not write
timeout-1 (none)Seconds the transaction may run before it is rolled back
transactionManagerThe single transaction manager beanWhich transaction manager to use when there is more than one

Every example on this page is a complete program that runs Spring Framework 7.0 against an in-memory H2 database, with no Spring Boot. Spring Boot sets up the same pieces for you, so the behaviour is identical in a Boot application.

A first transaction, shown running

An order has two steps: insert the order, then take one item out of stock. The stock table refuses negative quantities, so the second order for the only book in stock fails halfway, after its insert has already run. That makes it easy to see whether the insert survives:

Java
import javax.sql.DataSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;

public class ProxyBasics {

    @Configuration
    @EnableTransactionManagement
    static class Config {
        @Bean
        DataSource dataSource() {
            return new DriverManagerDataSource("jdbc:h2:mem:shop;DB_CLOSE_DELAY=-1");
        }

        @Bean
        JdbcTemplate jdbc(DataSource dataSource) {
            JdbcTemplate jdbc = new JdbcTemplate(dataSource);
            jdbc.execute("CREATE TABLE orders (id INT PRIMARY KEY, item VARCHAR(20))");
            jdbc.execute("CREATE TABLE stock (item VARCHAR(20) PRIMARY KEY,"
                    + " qty INT CHECK (qty >= 0))");
            jdbc.update("INSERT INTO stock VALUES ('book', 1)");
            return jdbc;
        }

        @Bean
        PlatformTransactionManager transactionManager(DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }

        @Bean
        OrderService orderService(JdbcTemplate jdbc) {
            return new OrderService(jdbc);
        }
    }

    static class OrderService {
        private final JdbcTemplate jdbc;

        OrderService(JdbcTemplate jdbc) {
            this.jdbc = jdbc;
        }

        @Transactional
        public void placeOrder(int id, String item) {
            System.out.println("  in placeOrder: transaction active = "
                    + TransactionSynchronizationManager.isActualTransactionActive()
                    + ", name = " + TransactionSynchronizationManager.getCurrentTransactionName());
            jdbc.update("INSERT INTO orders VALUES (?, ?)", id, item);
            jdbc.update("UPDATE stock SET qty = qty - 1 WHERE item = ?", item);
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            OrderService service = context.getBean(OrderService.class);
            JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
            System.out.println("Bean class: " + service.getClass().getName());
            System.out.println("Outside: transaction active = "
                    + TransactionSynchronizationManager.isActualTransactionActive());

            System.out.println("Order 1 (one book in stock):");
            service.placeOrder(1, "book");
            System.out.println("Order 2 (stock is now 0):");
            try {
                service.placeOrder(2, "book");
            } catch (RuntimeException e) {
                System.out.println("  failed: " + e.getClass().getSimpleName());
            }
            System.out.println("Orders saved: "
                    + jdbc.queryForList("SELECT id FROM orders", Integer.class));
            System.out.println("Stock left : "
                    + jdbc.queryForObject("SELECT qty FROM stock", Integer.class));
        }
    }
}
Output
Bean class: ProxyBasics$OrderService$$SpringCGLIB$$0
Outside: transaction active = false
Order 1 (one book in stock):
  in placeOrder: transaction active = true, name = ProxyBasics$OrderService.placeOrder
Order 2 (stock is now 0):
  in placeOrder: transaction active = true, name = ProxyBasics$OrderService.placeOrder
  failed: DataIntegrityViolationException
Orders saved: [1]
Stock left : 0
  • The bean's class is ProxyBasics$OrderService$$SpringCGLIB$$0, a subclass of OrderService generated at startup. That is the proxy; the code that calls it never sees the plain OrderService.
  • Outside the method, no transaction is active. Inside, one is, and its name is the class and method that started it.
  • Order 2's INSERT succeeded, then the UPDATE broke the check constraint and threw DataIntegrityViolationException. The proxy saw a runtime exception and rolled back, so only order 1 is saved and the stock is 0, not -1.

Spring Boot creates class-based (CGLIB) proxies by default. Plain Spring creates an interface-based proxy when the bean implements an interface, and a CGLIB one otherwise; both behave the same for the examples here.

Rollback rules: which exceptions roll back

The proxy decides between commit and rollback from one thing: the exception the method throws, if any. By default, a RuntimeException or an Error rolls back, and a checked exception commits. This program records the outcome of four failing payments with a TransactionSynchronization, a callback Spring runs after each transaction completes:

Java
import java.io.IOException;
import javax.sql.DataSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

public class RollbackRules {

    @Configuration
    @EnableTransactionManagement
    static class Config {
        @Bean
        DataSource dataSource() {
            return new DriverManagerDataSource("jdbc:h2:mem:rules;DB_CLOSE_DELAY=-1");
        }

        @Bean
        JdbcTemplate jdbc(DataSource dataSource) {
            JdbcTemplate jdbc = new JdbcTemplate(dataSource);
            jdbc.execute("CREATE TABLE payments (id INT PRIMARY KEY)");
            return jdbc;
        }

        @Bean
        PlatformTransactionManager transactionManager(DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }

        @Bean
        PaymentService paymentService(JdbcTemplate jdbc) {
            return new PaymentService(jdbc);
        }
    }

    static class PaymentService {
        private final JdbcTemplate jdbc;

        PaymentService(JdbcTemplate jdbc) {
            this.jdbc = jdbc;
        }

        private void insertAndReport(int id) {
            TransactionSynchronization report = new TransactionSynchronization() {
                @Override
                public void afterCompletion(int status) {
                    System.out.println("  transaction " + (status == STATUS_COMMITTED
                            ? "COMMITTED" : "ROLLED BACK"));
                }
            };
            TransactionSynchronizationManager.registerSynchronization(report);
            jdbc.update("INSERT INTO payments VALUES (?)", id);
        }

        @Transactional
        public void uncheckedFailure(int id) {
            insertAndReport(id);
            throw new IllegalStateException("card declined");
        }

        @Transactional
        public void checkedFailure(int id) throws IOException {
            insertAndReport(id);
            throw new IOException("bank unreachable");
        }

        @Transactional(rollbackFor = Exception.class)
        public void checkedFailureWithRollbackFor(int id) throws IOException {
            insertAndReport(id);
            throw new IOException("bank unreachable");
        }

        @Transactional
        public void caughtFailure(int id) {
            insertAndReport(id);
            try {
                throw new IllegalStateException("fraud check failed");
            } catch (IllegalStateException e) {
                System.out.println("  caught inside the method: " + e.getMessage());
            }
        }
    }

    interface Call {
        void run() throws Exception;
    }

    static void attempt(String label, Call call) {
        System.out.println(label);
        try {
            call.run();
        } catch (Exception e) {
            System.out.println("  caller sees "
                    + e.getClass().getSimpleName() + ": " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            PaymentService service = context.getBean(PaymentService.class);
            attempt("1. RuntimeException:", () -> service.uncheckedFailure(1));
            attempt("2. Checked IOException:", () -> service.checkedFailure(2));
            attempt("3. IOException with rollbackFor = Exception.class:",
                    () -> service.checkedFailureWithRollbackFor(3));
            attempt("4. Exception caught inside the method:", () -> service.caughtFailure(4));
            JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
            System.out.println("Payments saved: "
                    + jdbc.queryForList("SELECT id FROM payments ORDER BY id", Integer.class));
        }
    }
}
Output
1. RuntimeException:
  transaction ROLLED BACK
  caller sees IllegalStateException: card declined
2. Checked IOException:
  transaction COMMITTED
  caller sees IOException: bank unreachable
3. IOException with rollbackFor = Exception.class:
  transaction ROLLED BACK
  caller sees IOException: bank unreachable
4. Exception caught inside the method:
  caught inside the method: fraud check failed
  transaction COMMITTED
Payments saved: [2, 4]
  • Case 1: the IllegalStateException is unchecked, so the transaction rolled back and payment 1 is gone.
  • Case 2: the IOException is checked, so the transaction committed, and the caller still received the exception. This is the trap behind most "the error was reported but the data was saved anyway" bugs: payment 2 is in the table.
  • Case 3: rollbackFor = Exception.class makes checked exceptions roll back too, so payment 3 is gone.
  • Case 4: the method caught its own exception and returned normally. The proxy never saw a failure, so the transaction committed and payment 4 was saved.

The default comes from EJB, where a checked exception was treated as an expected business outcome rather than a failure. If your code uses checked exceptions for failures, there are three ways to change it:

  • Per method: @Transactional(rollbackFor = Exception.class), as in case 3.
  • For the whole application, from Spring Framework 6.2: @EnableTransactionManagement(rollbackOn = RollbackOn.ALL_EXCEPTIONS). Running this program with that setting makes case 2 roll back as well.
  • Inside the method, when you catch an exception but still want to roll back: TransactionAspectSupport.currentTransactionStatus().setRollbackOnly().

noRollbackFor does the opposite: it lists runtime exceptions that should still commit, for example a validation error after which the work done so far should be kept.

Rollback-only: the UnexpectedRollbackException

Catching an exception does not always save the transaction. When the exception comes from another @Transactional method that joined the same transaction, that method's proxy has already marked the whole transaction rollback-only before the caller catches anything. Here an order service calls an email service that fails, and catches the failure so that the order can go ahead:

Java
import javax.sql.DataSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

public class RollbackOnly {

    @Configuration
    @EnableTransactionManagement
    static class Config {
        @Bean
        DataSource dataSource() {
            return new DriverManagerDataSource("jdbc:h2:mem:only;DB_CLOSE_DELAY=-1");
        }

        @Bean
        JdbcTemplate jdbc(DataSource dataSource) {
            JdbcTemplate jdbc = new JdbcTemplate(dataSource);
            jdbc.execute("CREATE TABLE orders (id INT PRIMARY KEY)");
            jdbc.execute("CREATE TABLE emails (order_id INT)");
            return jdbc;
        }

        @Bean
        PlatformTransactionManager transactionManager(DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }

        @Bean
        EmailService emailService(JdbcTemplate jdbc) {
            return new EmailService(jdbc);
        }

        @Bean
        OrderService orderService(JdbcTemplate jdbc, EmailService emails) {
            return new OrderService(jdbc, emails);
        }
    }

    static class EmailService {
        private final JdbcTemplate jdbc;

        EmailService(JdbcTemplate jdbc) {
            this.jdbc = jdbc;
        }

        @Transactional   // REQUIRED: joins the caller's transaction
        public void queueConfirmation(int orderId) {
            jdbc.update("INSERT INTO emails VALUES (?)", orderId);
            throw new IllegalStateException("mail template missing");
        }
    }

    static class OrderService {
        private final JdbcTemplate jdbc;
        private final EmailService emails;

        OrderService(JdbcTemplate jdbc, EmailService emails) {
            this.jdbc = jdbc;
            this.emails = emails;
        }

        @Transactional
        public void placeOrder(int id) {
            jdbc.update("INSERT INTO orders VALUES (?)", id);
            try {
                emails.queueConfirmation(id);
            } catch (IllegalStateException e) {
                System.out.println("placeOrder caught: " + e.getMessage() + ", carrying on");
            }
            System.out.println("placeOrder returns normally");
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            try {
                context.getBean(OrderService.class).placeOrder(1);
            } catch (RuntimeException e) {
                System.out.println("Caller sees " + e.getClass().getSimpleName() + ":");
                System.out.println("  " + e.getMessage());
            }
            JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
            System.out.println("Orders saved: "
                    + jdbc.queryForList("SELECT id FROM orders", Integer.class));
        }
    }
}
Output
placeOrder caught: mail template missing, carrying on
placeOrder returns normally
Caller sees UnexpectedRollbackException:
  Transaction rolled back because it has been marked as rollback-only
Orders saved: []
  • placeOrder caught the exception and returned normally, so it looked like it would commit.
  • But queueConfirmation ran with the default REQUIRED propagation, so it joined the order's transaction. When it threw, its proxy marked that shared transaction rollback-only.
  • At the end of placeOrder, the proxy tried to commit, found the mark, rolled back instead, and threw UnexpectedRollbackException to tell the caller that the commit it expected did not happen. The order was not saved.

The exception is Spring refusing to commit half of a transaction that one participant already declared failed. Fix it by deciding what the email step really is:

  • If the order must not be saved without the email, let the exception propagate and do not catch it.
  • If the email is optional, run it in its own transaction with REQUIRES_NEW, or as a NESTED step, so that its failure is rolled back on its own. Both are shown in the next section.
  • If the email does not need the database at all, take @Transactional off it.

Propagation: joining, starting or refusing a transaction

Propagation decides what a @Transactional method does when a transaction is already running on the thread. Three settings change the outcome most often, so this program runs one example of each:

Java
import javax.sql.DataSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;

public class PropagationDemo {

    @Configuration
    @EnableTransactionManagement
    static class Config {
        @Bean
        DataSource dataSource() {
            return new DriverManagerDataSource("jdbc:h2:mem:prop;DB_CLOSE_DELAY=-1");
        }

        @Bean
        JdbcTemplate jdbc(DataSource dataSource) {
            JdbcTemplate jdbc = new JdbcTemplate(dataSource);
            jdbc.execute("CREATE TABLE log (message VARCHAR(40))");
            return jdbc;
        }

        @Bean
        PlatformTransactionManager transactionManager(DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }

        @Bean
        Inner inner(JdbcTemplate jdbc) {
            return new Inner(jdbc);
        }

        @Bean
        Outer outer(JdbcTemplate jdbc, Inner inner) {
            return new Outer(jdbc, inner);
        }
    }

    static Object rows(JdbcTemplate jdbc) {
        return jdbc.queryForList("SELECT message FROM log", String.class);
    }

    static String tx() {
        return TransactionSynchronizationManager.getCurrentTransactionName();
    }

    static class Inner {
        private final JdbcTemplate jdbc;

        Inner(JdbcTemplate jdbc) {
            this.jdbc = jdbc;
        }

        @Transactional(propagation = Propagation.REQUIRES_NEW)
        public void audit(String message) {
            System.out.println("  audit runs in      " + tx());
            jdbc.update("INSERT INTO log VALUES (?)", message);
        }

        @Transactional(propagation = Propagation.NESTED)
        public void optionalStep(String message) {
            System.out.println("  optionalStep runs in " + tx() + " (savepoint)");
            jdbc.update("INSERT INTO log VALUES (?)", message);
            throw new IllegalStateException("optional step failed");
        }

        @Transactional(propagation = Propagation.MANDATORY)
        public void mustJoin() {
            System.out.println("  mustJoin runs in " + tx());
        }
    }

    static class Outer {
        private final JdbcTemplate jdbc;
        private final Inner inner;

        Outer(JdbcTemplate jdbc, Inner inner) {
            this.jdbc = jdbc;
            this.inner = inner;
        }

        @Transactional
        public void failingOrder() {
            System.out.println("  failingOrder runs in " + tx());
            jdbc.update("INSERT INTO log VALUES ('order A')");
            inner.audit("audit for order A");
            throw new IllegalStateException("order A failed");
        }

        @Transactional
        public void orderWithOptionalStep() {
            jdbc.update("INSERT INTO log VALUES ('order B')");
            try {
                inner.optionalStep("optional step for B");
            } catch (IllegalStateException e) {
                System.out.println("  caught: " + e.getMessage());
            }
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            Outer outer = context.getBean(Outer.class);
            Inner inner = context.getBean(Inner.class);
            JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);

            System.out.println("REQUIRES_NEW inside a transaction that fails:");
            try {
                outer.failingOrder();
            } catch (IllegalStateException e) {
                System.out.println("  caller sees: " + e.getMessage());
            }
            System.out.println("  rows: " + rows(jdbc));

            jdbc.update("DELETE FROM log");
            System.out.println("NESTED step that fails, caught by the caller:");
            outer.orderWithOptionalStep();
            System.out.println("  rows: " + rows(jdbc));

            System.out.println("MANDATORY called with no transaction:");
            try {
                inner.mustJoin();
            } catch (RuntimeException e) {
                System.out.println("  " + e.getClass().getSimpleName() + ": " + e.getMessage());
            }
        }
    }
}
Output
REQUIRES_NEW inside a transaction that fails:
  failingOrder runs in PropagationDemo$Outer.failingOrder
  audit runs in      PropagationDemo$Inner.audit
  caller sees: order A failed
  rows: [audit for order A]
NESTED step that fails, caught by the caller:
  optionalStep runs in PropagationDemo$Outer.orderWithOptionalStep (savepoint)
  caught: optional step failed
  rows: [order B]
MANDATORY called with no transaction:
  IllegalTransactionStateException: No existing transaction found for transaction marked with propagation 'mandatory'
  • REQUIRES_NEW: audit ran in a transaction of its own, named after itself, and committed when it returned. The outer transaction then failed and rolled back order A, but the audit row stayed. This is the usual way to record a failure that should survive the rollback.
  • NESTED: optionalStep ran inside the outer transaction, behind a savepoint. Its failure rolled back to the savepoint only, so its own row disappeared, while order B committed. There is no UnexpectedRollbackException, unlike the previous section.
  • MANDATORY: called with no transaction running, the method refused to start, with IllegalTransactionStateException. It marks methods that must only be called as part of a larger transaction.
The seven propagation settings
PropagationTransaction already runningNo transaction running
REQUIRED (default)Joins itStarts one
REQUIRES_NEWSuspends it and starts a new oneStarts one
NESTEDRuns behind a savepoint inside itStarts one
SUPPORTSJoins itRuns without a transaction
NOT_SUPPORTEDSuspends it and runs without oneRuns without a transaction
MANDATORYJoins itThrows IllegalTransactionStateException
NEVERThrows IllegalTransactionStateExceptionRuns without a transaction

Two costs come with the settings that separate work:

  • REQUIRES_NEW holds two database connections at once, because the outer transaction keeps its connection while suspended. Under load, every request can end up holding one connection and waiting for a second, and a small pool runs dry. It can also deadlock, if the new transaction needs a row that the suspended one has locked.
  • NESTED needs savepoints. DataSourceTransactionManager supports them on JDBC drivers that do; with JpaTransactionManager, savepoints are not available by default.

Isolation levels

Isolation decides how much one transaction sees of others that run at the same time. Higher levels prevent more anomalies, at the cost of more locking or more transactions failing and having to be retried:

Anomalies each level prevents, as defined by the SQL standard
IsolationDirty readNon-repeatable readPhantom read
READ_UNCOMMITTEDPossiblePossiblePossible
READ_COMMITTEDPreventedPossiblePossible
REPEATABLE_READPreventedPreventedPossible
SERIALIZABLEPreventedPreventedPrevented
  • A dirty read sees another transaction's uncommitted changes, which may still be rolled back.
  • A non-repeatable read reads the same row twice and gets two different values, because another transaction committed in between.
  • A phantom read runs the same query twice and gets a different set of rows.

The default, Isolation.DEFAULT, keeps the database's own level: READ_COMMITTED for PostgreSQL, Oracle, SQL Server and H2, and REPEATABLE_READ for MySQL with InnoDB. Databases also go beyond the standard's minimum; PostgreSQL's REPEATABLE_READ, for example, prevents phantom reads too. Raise the level only for the transactions that need it, such as a report that must see one consistent snapshot:

Java
@Transactional(isolation = Isolation.REPEATABLE_READ, readOnly = true)
public MonthlyReport buildReport(YearMonth month) {
    // every query in this method sees the same snapshot of the data
}

Isolation applies only when the method starts a new transaction. A method that joins an existing transaction runs at that transaction's level, whatever its own annotation says.

Calls that skip the proxy

The transaction exists only for calls that pass through the proxy. A call on this, from one method of a bean to another, goes straight to the target object and never reaches the proxy. This program tries five kinds of call and prints whether each one got a transaction:

Java
import javax.sql.DataSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;

public class SelfInvocation {

    @Configuration
    @EnableTransactionManagement
    static class Config {
        @Bean
        DataSource dataSource() {
            return new DriverManagerDataSource("jdbc:h2:mem:self;DB_CLOSE_DELAY=-1");
        }

        @Bean
        PlatformTransactionManager transactionManager(DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }

        @Bean
        ImportService importService() {
            return new ImportService();
        }

        @Bean
        RowWriter rowWriter() {
            return new RowWriter();
        }
    }

    static void report(String where) {
        System.out.println("  " + where + ": transaction active = "
                + TransactionSynchronizationManager.isActualTransactionActive());
    }

    static class ImportService {
        public void importAll() {
            report("importAll (not annotated)");
            this.saveBatch();          // a call on 'this' never reaches the proxy
        }

        @Transactional
        public void saveBatch() {
            report("saveBatch (@Transactional)");
        }

        @Transactional
        void packagePrivateSave() {
            report("packagePrivateSave (@Transactional, package-private)");
        }

        @Transactional
        public final void finalSave() {
            report("finalSave (@Transactional, final)");
        }
    }

    static class RowWriter {
        @Transactional
        public void saveBatch() {
            report("RowWriter.saveBatch (@Transactional, another bean)");
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            ImportService service = context.getBean(ImportService.class);
            System.out.println("Calling saveBatch through importAll:");
            service.importAll();
            System.out.println("Calling saveBatch directly on the bean:");
            service.saveBatch();
            System.out.println("Calling a package-private method on the bean:");
            service.packagePrivateSave();
            System.out.println("Calling a final method on the bean:");
            service.finalSave();
            System.out.println("Calling a method on another bean:");
            context.getBean(RowWriter.class).saveBatch();
        }
    }
}
Output
Calling saveBatch through importAll:
  importAll (not annotated): transaction active = false
  saveBatch (@Transactional): transaction active = false
Calling saveBatch directly on the bean:
  saveBatch (@Transactional): transaction active = true
Calling a package-private method on the bean:
  packagePrivateSave (@Transactional, package-private): transaction active = true
Calling a final method on the bean:
  finalSave (@Transactional, final): transaction active = false
Calling a method on another bean:
  RowWriter.saveBatch (@Transactional, another bean): transaction active = true
Nov 14, 2026 9:19:00 PM org.springframework.aop.framework.CglibAopProxy doValidateClass
WARNING: Public final method [public final void SelfInvocation$ImportService.finalSave()] cannot get proxied via CGLIB, consider removing the final marker or using interface-based JDK proxies.
  • Through importAll, saveBatch ran with no transaction, although it is annotated. this.saveBatch() called the method on the target object directly.
  • Called on the bean from outside, the same method got a transaction, because the call went through the proxy.
  • The package-private method got a transaction too. Class-based proxies have handled protected and package-private methods since Spring Framework 6.0; private methods can never be proxied.
  • The final method got none. A CGLIB subclass cannot override a final method, so Spring printed the warning at the end of the output when the context started. It appears last because it goes to standard error, and its first line, the log record's date and time, differs on every run.
  • Moved to another bean, saveBatch got a transaction, because the call now goes through that bean's proxy.

The fix for self-invocation is to make the call go through a proxy. Moving the transactional method to another bean, as RowWriter does, is the clearest way. Injecting the bean into itself, with @Lazy to avoid a circular reference, also works but hides the reason. For a block that does not deserve its own method, use TransactionTemplate, which starts a transaction around a lambda without any proxy. The Spring AOP page explains how these proxies are built.

Transactions do not cross threads

The transaction manager binds the connection to the thread that called the method. Code that runs on any other thread, such as a CompletableFuture, an @Async method or a parallel stream, sees no transaction. Here a signup writes one row on the request thread and a second one from a pool thread, then fails:

Java
import java.util.concurrent.CompletableFuture;
import javax.sql.DataSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;

public class ThreadBoundary {

    @Configuration
    @EnableTransactionManagement
    static class Config {
        @Bean
        DataSource dataSource() {
            return new DriverManagerDataSource("jdbc:h2:mem:threads;DB_CLOSE_DELAY=-1");
        }

        @Bean
        JdbcTemplate jdbc(DataSource dataSource) {
            JdbcTemplate jdbc = new JdbcTemplate(dataSource);
            jdbc.execute("CREATE TABLE events (name VARCHAR(30))");
            return jdbc;
        }

        @Bean
        PlatformTransactionManager transactionManager(DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }

        @Bean
        SignupService signupService(JdbcTemplate jdbc) {
            return new SignupService(jdbc);
        }
    }

    static class SignupService {
        private final JdbcTemplate jdbc;

        SignupService(JdbcTemplate jdbc) {
            this.jdbc = jdbc;
        }

        @Transactional
        public void signUp() {
            System.out.println("request thread: transaction active = "
                    + TransactionSynchronizationManager.isActualTransactionActive());
            jdbc.update("INSERT INTO events VALUES ('user created')");
            CompletableFuture.runAsync(() -> {
                System.out.println("pool thread   : transaction active = "
                        + TransactionSynchronizationManager.isActualTransactionActive());
                jdbc.update("INSERT INTO events VALUES ('welcome email queued')");
            }).join();
            throw new IllegalStateException("signup failed after the email was queued");
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            try {
                context.getBean(SignupService.class).signUp();
            } catch (IllegalStateException e) {
                System.out.println("caller sees    : " + e.getMessage());
            }
            JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
            System.out.println("rows left      : "
                    + jdbc.queryForList("SELECT name FROM events", String.class));
        }
    }
}
Output
request thread: transaction active = true
pool thread   : transaction active = false
caller sees    : signup failed after the email was queued
rows left      : [welcome email queued]
  • The pool thread found no transaction, so JdbcTemplate took a fresh connection in auto-commit mode, and its insert committed at once.
  • When signUp failed, the rollback removed user created, but welcome email queued stayed: an email was queued for a user who does not exist.

Keep all the writes of one transaction on the thread that started it. Work that must happen after the data is saved, such as sending the email, belongs after the commit: an event handled with @TransactionalEventListener runs only once the transaction has committed, as the Spring events page shows. The ThreadLocal page explains why values bound to one thread are invisible to others.

readOnly is a hint, not a guard

readOnly = true tells the transaction manager and the database that the transaction will not write. They may use it to skip work, but nothing promises that a write will be refused. This report method contains a bug, an UPDATE that sets every price to 0:

Java
import javax.sql.DataSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

public class ReadOnlyHint {

    @Configuration
    @EnableTransactionManagement
    static class Config {
        @Bean
        DataSource dataSource() {
            return new DriverManagerDataSource("jdbc:h2:mem:ro;DB_CLOSE_DELAY=-1");
        }

        @Bean
        JdbcTemplate jdbc(DataSource dataSource) {
            JdbcTemplate jdbc = new JdbcTemplate(dataSource);
            jdbc.execute("CREATE TABLE prices (item VARCHAR(20), price INT)");
            jdbc.update("INSERT INTO prices VALUES ('book', 20)");
            return jdbc;
        }

        @Bean
        PlatformTransactionManager transactionManager(DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }

        @Bean
        ReportService reportService(JdbcTemplate jdbc) {
            return new ReportService(jdbc);
        }
    }

    static class ReportService {
        private final JdbcTemplate jdbc;

        ReportService(JdbcTemplate jdbc) {
            this.jdbc = jdbc;
        }

        @Transactional(readOnly = true)
        public int priceReport() {
            jdbc.update("UPDATE prices SET price = 0");   // a bug: a write in a read-only method
            return jdbc.queryForObject("SELECT price FROM prices", Integer.class);
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            try {
                System.out.println("price seen in the report: "
                        + context.getBean(ReportService.class).priceReport());
            } catch (RuntimeException e) {
                System.out.println("write refused: " + e.getClass().getSimpleName());
            }
            JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
            System.out.println("price in the database   : "
                    + jdbc.queryForObject("SELECT price FROM prices", Integer.class));
        }
    }
}
Output
price seen in the report: 0
price in the database   : 0
  • H2 accepted the write inside the read-only transaction, and the change was committed: the price in the database is now 0.
  • DataSourceTransactionManager passes the hint on as Connection.setReadOnly(true), and each JDBC driver decides what that means. The PostgreSQL driver starts a read-only transaction, and the database then rejects the UPDATE. H2 ignores it, as the output shows.
  • With JPA and Hibernate, readOnly = true also switches off dirty checking and flushing, so changes made to loaded entities are not written back. That saves memory and time in large read-only queries.

Use readOnly = true for queries, for the performance it allows, but enforce read-only access with database permissions if a write would be dangerous.

Other traps in real applications

  • Lazy loading after the transaction: with JPA, a lazy collection read after the @Transactional method has returned throws LazyInitializationException, because the session has closed. Load what the caller needs inside the transaction, with a fetch join or an entity graph.
  • Slow work inside a transaction: a remote call or a file upload inside a @Transactional method keeps the database connection, and any locks, for its whole duration. Do slow work before the transaction starts or after it ends.
  • Tests that roll back: a test method annotated with @Transactional is rolled back after it runs by default. That keeps tests independent, but it also means the code under test never commits, so behaviour that happens at commit, such as constraint checks deferred to commit or @TransactionalEventListener handlers, is never tested.
  • The wrong layer: put @Transactional on the service method that defines the unit of work. Spring Data repository methods already run in their own transaction each, so a service that calls two repository methods without its own annotation makes two separate transactions, and the first one stays committed if the second fails.
  • Exceptions translated too late: when a constraint is only checked on flush or commit, as JPA does by default, the exception appears when the proxy commits, after your method has returned. A try block inside the method cannot catch it.

Choosing the right settings

Common situations and the settings that fit them
SituationSetting
A service method that writes, the usual case@Transactional with the defaults
Failures reported with checked exceptionsrollbackFor = Exception.class, or RollbackOn.ALL_EXCEPTIONS for the whole application
A record that must survive the caller's rollback, such as an audit entryREQUIRES_NEW, keeping it short
An optional step whose failure should not stop the restNESTED on JDBC, or REQUIRES_NEW
A method that only makes sense inside a larger transactionMANDATORY
Queries and reportsreadOnly = true, with a higher isolation level only when one consistent snapshot is needed
A transactional block inside a method, or a call on the same beanTransactionTemplate
Work that must happen only after the data is committed@TransactionalEventListener

Most production problems come from four rules on this page: checked exceptions commit by default, a caught exception from a joined method still rolls everything back, calls on this and on final methods get no transaction, and other threads are outside the transaction. For transactions in plain JDBC, without Spring, see JDBC transactions and batch updates.