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 first transaction, shown running Rollback rules: which exceptions roll back Rollback-only: the UnexpectedRollbackException Propagation: joining, starting or refusing a transaction Isolation levels Calls that skip the proxy Transactions do not cross threads readOnly is a hint, not a guard Other traps in real applications Choosing the right settings
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()rollback()
@Transactional
- A proxy: when a bean has
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.@Transactional - A transaction manager: before the method runs, the proxy asks the
to begin a transaction, and afterwards to commit or roll back.PlatformTransactionManager does this for JDBC, andDataSourceTransactionManager for JPA.JpaTransactionManager - A thread-bound connection: the transaction manager binds the connection to the current thread with a
.ThreadLocal , Spring Data repositories and JPA all look there first, which is how they take part in the transaction without being passed the connection.JdbcTemplate
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:
| Attribute | Default | What it controls |
|---|---|---|
propagation | REQUIRED | Whether to join a transaction that is already running, start a new one, or run without one |
isolation | DEFAULT | How much the transaction sees of other transactions' changes |
rollbackFornoRollbackFor | Roll back on RuntimeExceptionError | Which exceptions cause a rollback |
readOnly | false | A hint that the transaction will not write |
timeout | -1 (none) | Seconds the transaction may run before it is rolled back |
transactionManager | The single transaction manager bean | Which 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:
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));
}
}
}
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
, a subclass ofProxyBasics$OrderService$$SpringCGLIB$$0 generated at startup. That is the proxy; the code that calls it never sees the plainOrderService .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
succeeded, then theINSERT broke the check constraint and threwUPDATE . The proxy saw a runtime exception and rolled back, so only order 1 is saved and the stock is 0, not -1.DataIntegrityViolationException
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 RuntimeExceptionErrorTransactionSynchronization
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));
}
}
}
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
is unchecked, so the transaction rolled back and payment 1 is gone.IllegalStateException - Case 2: the
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.IOException - Case 3:
makes checked exceptions roll back too, so payment 3 is gone.rollbackFor = Exception.class - 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:
, as in case 3.@Transactional(rollbackFor = Exception.class) - For the whole application, from Spring Framework 6.2:
. Running this program with that setting makes case 2 roll back as well.@EnableTransactionManagement(rollbackOn = RollbackOn.ALL_EXCEPTIONS) - Inside the method, when you catch an exception but still want to roll back:
.TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
noRollbackFor
Rollback-only: the UnexpectedRollbackException
Catching an exception does not always save the transaction. When the exception comes from another @Transactional
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));
}
}
}
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: []
caught the exception and returned normally, so it looked like it would commit.placeOrder- But
ran with the defaultqueueConfirmation propagation, so it joined the order's transaction. When it threw, its proxy marked that shared transaction rollback-only.REQUIRED - At the end of
, the proxy tried to commit, found the mark, rolled back instead, and threwplaceOrder to tell the caller that the commit it expected did not happen. The order was not saved.UnexpectedRollbackException
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
, or as aREQUIRES_NEW step, so that its failure is rolled back on its own. Both are shown in the next section.NESTED - If the email does not need the database at all, take
off it.@Transactional
Propagation: joining, starting or refusing a transaction
Propagation decides what a @Transactional
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());
}
}
}
}
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 ran in a transaction of its own, named after itself, and committed when it returned. The outer transaction then failed and rolled backaudit , but the audit row stayed. This is the usual way to record a failure that should survive the rollback.order A :NESTED ran inside the outer transaction, behind a savepoint. Its failure rolled back to the savepoint only, so its own row disappeared, whileoptionalStep committed. There is noorder B , unlike the previous section.UnexpectedRollbackException : called with no transaction running, the method refused to start, withMANDATORY . It marks methods that must only be called as part of a larger transaction.IllegalTransactionStateException
| Propagation | Transaction already running | No transaction running |
|---|---|---|
REQUIRED | Joins it | Starts one |
REQUIRES_NEW | Suspends it and starts a new one | Starts one |
NESTED | Runs behind a savepoint inside it | Starts one |
SUPPORTS | Joins it | Runs without a transaction |
NOT_SUPPORTED | Suspends it and runs without one | Runs without a transaction |
MANDATORY | Joins it | Throws IllegalTransactionStateException |
NEVER | Throws IllegalTransactionStateException | Runs without a transaction |
Two costs come with the settings that separate work:
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.REQUIRES_NEW needs savepoints.NESTED supports them on JDBC drivers that do; withDataSourceTransactionManager , savepoints are not available by default.JpaTransactionManager
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:
| Isolation | Dirty read | Non-repeatable read | Phantom read |
|---|---|---|---|
READ_UNCOMMITTED | Possible | Possible | Possible |
READ_COMMITTED | Prevented | Possible | Possible |
REPEATABLE_READ | Prevented | Prevented | Possible |
SERIALIZABLE | Prevented | Prevented | Prevented |
- 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.DEFAULTREAD_COMMITTEDREPEATABLE_READREPEATABLE_READ
@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
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();
}
}
}
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 ran with no transaction, although it is annotated.saveBatch called the method on the target object directly.this.saveBatch() - 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
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.final - Moved to another bean,
got a transaction, because the call now goes through that bean's proxy.saveBatch
The fix for self-invocation is to make the call go through a proxy. Moving the transactional method to another bean, as RowWriter@LazyTransactionTemplate
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@Async
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));
}
}
}
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
took a fresh connection in auto-commit mode, and its insert committed at once.JdbcTemplate - When
failed, the rollback removedsignUp , butuser created stayed: an email was queued for a user who does not exist.welcome email queued
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
readOnly is a hint, not a guard
readOnly = trueUPDATE
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));
}
}
}
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.
passes the hint on asDataSourceTransactionManager , and each JDBC driver decides what that means. The PostgreSQL driver starts a read-only transaction, and the database then rejects theConnection.setReadOnly(true) . H2 ignores it, as the output shows.UPDATE- With JPA and Hibernate,
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.readOnly = true
Use readOnly = true
Other traps in real applications
- Lazy loading after the transaction: with JPA, a lazy collection read after the
method has returned throws@Transactional , because the session has closed. Load what the caller needs inside the transaction, with a fetch join or an entity graph.LazyInitializationException - Slow work inside a transaction: a remote call or a file upload inside a
method keeps the database connection, and any locks, for its whole duration. Do slow work before the transaction starts or after it ends.@Transactional - Tests that roll back: a test method annotated with
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@Transactional handlers, is never tested.@TransactionalEventListener - The wrong layer: put
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.@Transactional - 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
block inside the method cannot catch it.try
Choosing the right settings
| Situation | Setting |
|---|---|
| A service method that writes, the usual case | @Transactional |
| Failures reported with checked exceptions | rollbackFor = Exception.classRollbackOn.ALL_EXCEPTIONS |
| A record that must survive the caller's rollback, such as an audit entry | REQUIRES_NEW |
| An optional step whose failure should not stop the rest | NESTEDREQUIRES_NEW |
| A method that only makes sense inside a larger transaction | MANDATORY |
| Queries and reports | readOnly = true |
| A transactional block inside a method, or a call on the same bean | TransactionTemplate |
| 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 thisfinal