DEV Community

Cover image for Spring Transactional pitfalls: self-invocation and rollback
duong vu
duong vu

Posted on Originally published at shippedcode.dev

Spring Transactional pitfalls: self-invocation and rollback

Originally published at Shipped Code.

You put @Transactional on a service method, an exception is thrown halfway through, and the first row is still in the database. Usually one of 2 things happened. The call never went through Spring's proxy, so there was no transaction at all, or the exception was a checked one, which commits by default. Most of the other pitfalls come from propagation. An inner REQUIRED method that fails dooms the whole outer transaction, while REQUIRES_NEW commits on its own.

Pitfall Symptom Fix
Self-invocation (this.place()) No transaction, rows saved before the exception stay Call through another bean, or use TransactionTemplate
Checked exception Method throws, data is committed anyway Throw unchecked domain exceptions; rollbackFor when you can't
Swallowed inner failure UnexpectedRollbackException at commit Don't catch and continue, or give the inner call REQUIRES_NEW
Audit row under REQUIRED Audit disappears with the failed operation REQUIRES_NEW for the audit write (needs a second connection)
NESTED with JPA NestedTransactionNotSupportedException Use REQUIRES_NEW, or plain JDBC with DataSourceTransactionManager
@Transactional on the test class Test passes, production fails at flush Flush in the test, or test without a test-managed transaction

TL;DR. Only calls that reach the bean through its proxy get a transaction. By default only RuntimeException and Error roll back. If an inner REQUIRED call fails, the outer transaction can't commit, even if you catch the exception. Each row above has a test below that fails first and passes after the fix.

What you'll learn:

  • how to predict when @Transactional silently does nothing;
  • which exceptions roll back, and how to choose between REQUIRED and REQUIRES_NEW;
  • how to prove each behaviour with a test, and which test setup hides bugs.

If you are chasing one bug, jump to its section. The (Advanced) section on threads and events can wait. I assume you write services with Spring Data JPA (the Java backend roadmap shows where that fits). Examples run on Spring Boot 4.2.0, Spring Framework 7.1.0, Hibernate ORM 7.4, Java 25 and PostgreSQL 18.

How @Transactional is applied

Spring does not change your class. At startup it wraps the bean in a proxy, a generated subclass that sits between callers and your object. When a call arrives, the proxy opens a transaction, calls your method, then commits or rolls back depending on how the method ended.

A caller calls orderService.place() through the Spring proxy, which begins the transaction and commits or rolls back, then delegates to the real OrderService; a call to this.place() inside OrderService goes straight to the method and skips the proxy, so no transaction starts

Because the proxy is a subclass, it can only intercept methods it can override. On Framework 7 with the default class-based proxies, public, protected and package-private methods all work (the reference says so since 6.0). A private method can't be overridden, and neither can a final one. I put @Transactional on 4 methods of one bean, each returning TransactionSynchronizationManager.isActualTransactionActive(), and called them from a test.

WARN o.s.aop.framework.CglibAopProxy : Public final method [public final boolean dev.duongvu.tx.VisibilityProbe.finalMethod()] cannot get proxied via CGLIB, consider removing the final marker or using interface-based JDK proxies.
public=true, protected=true, package=true, final=false
Enter fullscreen mode Exit fullscreen mode

The final method compiles, runs and gets no transaction. The only hint is one WARN line at startup.

Self-invocation skips the transaction

Self-invocation is the case you will hit most often, and the proxy explains it. Here placeAll() loops over customers and calls place() on itself.

public void placeAll(List<String> customers) {
    for (String c : customers) place(c);   // this.place(): no proxy
}

@Transactional
public void place(String customer) {
    System.out.println("tx active in place(): "
            + TransactionSynchronizationManager.isActualTransactionActive());
    orders.save(new ShopOrder(customer));
    if (customer.isBlank()) throw new IllegalArgumentException("customer is blank");
}
Enter fullscreen mode Exit fullscreen mode

The intent is that a blank customer never gets an order, so after this test only alice should be in the table.

@Test
void selfInvocation_blankCustomerIsNotSaved() {
    assertThatThrownBy(() -> orderService.placeAll(List.of("alice", " ")))
            .isInstanceOf(IllegalArgumentException.class);
    assertThat(orders.count()).isEqualTo(1);
}
Enter fullscreen mode Exit fullscreen mode
tx active in place(): false
tx active in place(): false
org.opentest4j.AssertionFailedError:
expected: 1L
 but was: 2L
Enter fullscreen mode Exit fullscreen mode

There was no transaction around place(). The save() call still worked because Spring Data repository methods have their own transaction, which committed the blank order before the exception.

You have 3 ways out, and I'd use them in this order:

  1. Move the method to another bean. OrderPlacer.place() carries the annotation, and OrderService calls placer.place(c). The call crosses a proxy and the test passes. It is also the clearest design, since "place one order" becomes a named unit of work.
  2. TransactionTemplate when you don't want a new class, or the boundary is smaller than a method (one commit per chunk of a batch). Spring Boot auto-configures the bean:
   public void placeAllWithTemplate(List<String> customers) {
       for (String c : customers) tx.executeWithoutResult(status -> place(c));
   }
Enter fullscreen mode Exit fullscreen mode

The output now shows tx active in place(): true and the count is 1.

  1. Self-injection means injecting the bean's own proxy into a field and calling self.place(c). A plain @Autowired self-field stops the application at startup, since Spring Boot 2.6 rejects circular references by default:
   The dependencies of some of the beans in the application context form a cycle:
   Relying upon circular references is discouraged and they are prohibited by default.
Enter fullscreen mode Exit fullscreen mode

With @Lazy on the field it starts, prints tx active in self.place(): true and leaves 1 row. It works, but the next reader has to guess why self exists. I avoid it.

Checked exceptions commit by default

By default Spring rolls back on RuntimeException and Error only. A checked exception thrown out of a @Transactional method lets the transaction commit, as the rollback docs say. The method threw, yet the row is there.

@Transactional
public void checkout(String customer) throws PaymentDeclinedException {   // a checked exception
    orders.save(new ShopOrder(customer));
    throw new PaymentDeclinedException("card declined");
}
Enter fullscreen mode Exit fullscreen mode

A test that expects an empty table after the exception fails.

expected: 0L
 but was: 1L
    at dev.duongvu.tx.TransactionPitfallsTest.checkedException_rollsBack(TransactionPitfallsTest.java:57)
Enter fullscreen mode Exit fullscreen mode

My preference is that services throw unchecked domain exceptions (OrderRejectedException extends RuntimeException), so the default rule is already right and nobody has to remember an attribute. When a checked exception comes from a library you can't change, add rollbackFor and leave a comment saying why.

// imagine this checked exception comes from a payment SDK you can't change
@Transactional(rollbackFor = PaymentDeclinedException.class)
public void checkoutRollbackFor(String customer) throws PaymentDeclinedException { ... }
Enter fullscreen mode Exit fullscreen mode

Both versions leave 0 rows. Since Framework 6.2 there is also a global switch, @EnableTransactionManagement(rollbackOn = RollbackOn.ALL_EXCEPTIONS), and its Javadoc recommends it for new code and for Kotlin. In an existing codebase I would check every method that relies on a checked exception committing before turning it on.

Why a caught exception still rolls back

The outer method places an order and tries to grant a bonus. If the bonus fails, it logs and moves on.

@Transactional
public void placeWithBonus(String customer) {
    orders.save(new ShopOrder(customer));
    try {
        bonus.grant(customer);          // @Transactional (REQUIRED), throws IllegalStateException
    } catch (IllegalStateException e) {
        System.out.println("bonus skipped: " + e.getMessage());
    }
}
Enter fullscreen mode Exit fullscreen mode
bonus skipped: bonus campaign closed
org.springframework.transaction.UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:803)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:757)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:687)
Enter fullscreen mode Exit fullscreen mode

grant() joined the outer transaction. When it threw a runtime exception, its proxy marked the shared transaction rollback-only, and your catch can't undo that mark. At commit time Spring rolls back and throws, so the caller is never told "saved" when the order is gone.

Warning: once an exception has passed through another @Transactional proxy that joined the same transaction, catching it does not make the transaction committable again. Either let it propagate, check the condition before calling, or run the optional step in its own transaction (REQUIRES_NEW, next section). With grantInOwnTx() marked REQUIRES_NEW, the same test saves the order.

Choosing REQUIRED, REQUIRES_NEW or NESTED

Propagation decides what happens when a transactional method is called while a transaction is already running. Three values cover nearly everything.

Propagation Joins the existing transaction? Use for Main trade-off
REQUIRED (default) Yes, or starts one Almost every service method One failure rolls back everything
REQUIRES_NEW No, suspends it and starts a new one Audit rows, "attempt" logs that must survive a rollback Holds a second connection while the outer one waits
NESTED Yes, with a savepoint Partial rollback in plain JDBC code Not available with JPA (see below)

The others (SUPPORTS, MANDATORY, NOT_SUPPORTED, NEVER) are rare in application code.

A typical case is an audit entry for every order attempt, including the ones that fail. With REQUIRED, the audit write joins the order's transaction and is rolled back with it.

@Transactional
public void placeAudited(String customer, boolean ownTx) {
    if (ownTx) audit.recordInOwnTx("attempt by " + customer);   // REQUIRES_NEW
    else audit.record("attempt by " + customer);                // REQUIRED
    orders.save(new ShopOrder(customer));
    throw new OrderRejectedException("out of stock");
}
Enter fullscreen mode Exit fullscreen mode

The test expects 0 orders and 1 audit row. Under REQUIRED it fails with expected: 1L but was: 0L on the audit count; under REQUIRES_NEW it passes, because the audit transaction committed before the order failed.

That second transaction needs its own connection, and the outer transaction keeps its connection while it waits. I reran the passing test with a pool of 1 connection and a 3-second timeout.

WARN org.hibernate.orm.jdbc.error : HikariPool-1 - Connection is not available, request timed out after 3000ms (total=1, active=1, idle=0, waiting=0)
org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction
Enter fullscreen mode Exit fullscreen mode

Warning: with the pool at its limit, REQUIRES_NEW waits for a connection that only the waiting thread can free. Under load, many requests doing this at once can drain the pool. The propagation docs advise a pool larger than the number of concurrent threads by at least 1. Calling a REQUIRES_NEW method inside a loop also opens and commits one transaction per iteration.

Older articles suggest NESTED for partial rollback, so I tried it on the default Spring Boot setup.

org.springframework.transaction.NestedTransactionNotSupportedException: Transaction manager does not allow nested transactions by default - specify 'nestedTransactionAllowed' property with value 'true'
Enter fullscreen mode Exit fullscreen mode

On Framework 6.2, JpaTransactionManager allowed nested transactions by default; in 7.1 it no longer does. Setting the flag to true with a TransactionManagerCustomizer<JpaTransactionManager> only changes the error to JpaDialect does not support savepoints - check your JPA provider's capabilities. The docs describe NESTED as mapped to JDBC savepoints, so it works with DataSourceTransactionManager and plain JDBC. With JPA and Hibernate, use REQUIRES_NEW or restructure the work.

readOnly = true and where the annotation goes

I put @Transactional on public service methods that form one business operation, and @Transactional(readOnly = true) on query methods. I avoid a blanket class-level annotation on large services, because every new method then silently inherits the class's settings. Controllers stay free of it, since the boundary belongs where the business rule lives.

What readOnly does depends on the stack. With Hibernate and PostgreSQL, I saw 2 concrete effects.

  • changing a loaded entity inside a readOnly method is not flushed; the row keeps status = 'NEW' afterwards;
  • calling save() on a new entity fails, because Spring also marks the JDBC connection read-only and PostgreSQL enforces it:
WARN org.hibernate.orm.jdbc.error : ERROR: cannot execute INSERT in a read-only transaction
Enter fullscreen mode Exit fullscreen mode

Don't rely on that second effect everywhere, though. The TransactionDefinition Javadoc calls readOnly a hint that will "not necessarily cause failure of write access attempts", so another database or transaction manager may accept the write. If a lazy collection loads fine in your controller even though the service already returned, check Open Session in View, covered in the N+1 post.

Threads and after-commit events (Advanced)

Spring binds the transaction to the current thread. Work you hand to another thread runs without it, whatever executor you use.

@Transactional
public String threadCheck() {
    boolean here = TransactionSynchronizationManager.isActualTransactionActive();
    boolean async = CompletableFuture
            .supplyAsync(TransactionSynchronizationManager::isActualTransactionActive).join();
    boolean virtual;
    try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {
        virtual = exec.submit(TransactionSynchronizationManager::isActualTransactionActive).get();
    } catch (Exception e) { throw new RuntimeException(e); }
    return "caller=" + here + ", supplyAsync=" + async + ", virtual thread=" + virtual;
}
Enter fullscreen mode Exit fullscreen mode
caller=true, supplyAsync=false, virtual thread=false
Enter fullscreen mode Exit fullscreen mode

Virtual threads don't change this; the virtual threads post goes further into them. The same applies to @Async methods, which run on another thread.

The opposite need is "send the confirmation email only if the order was really saved". @TransactionalEventListener with phase = AFTER_COMMIT does that.

@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void on(OrderPlaced event) {
    sent.add("confirmation to " + event.customer());
}
Enter fullscreen mode Exit fullscreen mode

The test places one valid order (for gina) and one blank one that throws after publishing its event. sent contains only confirmation to gina; the failed order's event was dropped with its rollback.

Gotchas

A transactional test can hide the bug. Annotating a test class with @Transactional makes the test framework roll everything back at the end, and Hibernate may never flush the pending changes. This method sets a status that breaks the table's check (status in ('NEW', 'PAID')) constraint.

@Transactional
public void markShipped(long id) {
    orders.findById(id).orElseThrow().setStatus("SHIPPED");
}
Enter fullscreen mode Exit fullscreen mode

In a @SpringBootTest @Transactional class, the test passes. Without @Transactional on the test, the commit flushes the update and PostgreSQL rejects it.

org.springframework.dao.DataIntegrityViolationException:
could not execute statement [ERROR: new row for relation "orders" violates check constraint "orders_status_check"
  Detail: Failing row contains (1, hank, SHIPPED).]
Enter fullscreen mode Exit fullscreen mode

For tests that check database rules, either call entityManager.flush() before the assertions or let the service commit and clean the tables in @BeforeEach, as the tests in this post do. These tests run against a real PostgreSQL; Testcontainers makes that repeatable in CI.

Slow calls inside a transaction hold a connection. An HTTP call to a payment provider inside @Transactional keeps a pooled connection busy for as long as the provider takes. Do the remote call before or after the transaction where you can.

@Transactional on a repository interface only wraps that repository call. It doesn't help a service whose 3 repository calls must succeed together; that boundary belongs on the service method.

Isolation levels get their own post, transaction isolation levels, with each anomaly reproduced. For transactions next to indexes and schema design, the database pillar covers the parts you use every day. Transactions that span several services (sagas, the outbox pattern) are a different topic. Next in this series, consistent API errors with ProblemDetail shows how to turn exceptions like OrderRejectedException into clean responses for the client.

Top comments (0)