Skip to content
javahacks.dev
Spring Framework

Spring Transaction Management Explained From Start to Finish

Spring transaction management explained: the Transactional annotation, the proxy and manager, propagation, rollback rules and common pitfalls.

5 min read
Summarize in AI
Flat illustration of a staircase from one version to the next, with the Spring, Hibernate, OpenJDK and Apache Maven logos.

Transactions keep data consistent: several changes succeed together or not at all. Spring lets you declare that with an annotation, and understanding what happens behind it prevents the usual surprises. Examples use Spring Framework 7 and Boot 4.

The basic use

java
@Service
public class TransferService {

    private final AccountRepository accounts;

    TransferService(AccountRepository accounts) { this.accounts = accounts; }

    @Transactional
    public void transfer(long from, long to, BigDecimal amount) {
        Account a = accounts.findById(from).orElseThrow();
        Account b = accounts.findById(to).orElseThrow();
        a.withdraw(amount);
        b.deposit(amount);
    }
}

If withdraw throws IllegalStateException for insufficient funds, the transaction rolls back and neither account changes. If the method returns normally, Spring commits. With JPA, changes to managed entities are flushed at commit, so no explicit save is needed.

What happens behind the annotation

  1. The bean is wrapped in a proxy, see AOP proxies and self-invocation.
  2. When a caller invokes transfer, the proxy's TransactionInterceptor asks the PlatformTransactionManager for a transaction.
  3. The manager opens a connection and sets auto-commit to false (JDBC), or begins a JPA transaction.
  4. The method runs. All repository calls in the same thread use the same connection, bound to the thread.
  5. On normal return, the manager commits. On a qualifying exception it rolls back. The connection returns to the pool.

Spring Boot auto-configures JpaTransactionManager or DataSourceTransactionManager depending on what is on the classpath.

Attributes that matter

java
@Transactional(
    propagation = Propagation.REQUIRED,
    isolation = Isolation.READ_COMMITTED,
    readOnly = false,
    timeout = 10,
    rollbackFor = IOException.class)
  • Propagation decides how a call joins an existing transaction; REQUIRED (join or create) is the default, see propagation levels.
  • Isolation controls visibility between concurrent transactions, see isolation levels.
  • readOnly is a hint that allows optimisations, see readOnly use.
  • rollbackFor adds exception types; checked exceptions do not roll back by default, see rollback rules.
  • timeout cancels transactions that run too long.

Where to put the annotation

Put it on service methods or classes, the unit of business work, not on repositories (which are already transactional) and not on controllers. Annotating at class level applies to every public method. Prefer the narrowest boundary that keeps the business operation atomic.

Programmatic control

When you need finer control, use TransactionTemplate:

java
tx.execute(status -> {
    repo.save(entity);
    return null;
});

It avoids the proxy limits and lets you run code after commit. See TransactionTemplate.

Keep transactions short

A transaction holds a connection and, depending on isolation, locks. Do not call a slow remote service or wait for user input inside. A transaction that makes an HTTP call keeps a database connection idle while the call runs, which exhausts the pool under load, see connection pool timeouts. Commit first, then call, or use an outbox, see distributed transactions.

Common pitfalls

  • @Transactional on a private method or an internal call is ignored.
  • A checked exception commits instead of rolling back.
  • Catching an exception inside the method hides it from Spring, so it commits.
  • Lazy loading outside the transaction fails, see LazyInitializationException.
  • Mixing @Transactional from different libraries (Spring's and Jakarta's) behaves alike but is configured differently.

Testing

Tests annotated with @Transactional roll back after each test by default, which keeps the database clean but can hide commit-time problems. Details are in testing transactions.

Isolation levels and what each allows

The isolation level decides which anomalies a transaction can see from others running at the same time. Most applications use the database default, and a few need a different one:

LevelDirty readNon-repeatable readPhantom read
READ_UNCOMMITTEDPossiblePossiblePossible
READ_COMMITTEDNoPossiblePossible
REPEATABLE_READNoNoPossible in the standard, not in MySQL InnoDB or PostgreSQL
SERIALIZABLENoNoNo

PostgreSQL defaults to READ_COMMITTED and MySQL's InnoDB to REPEATABLE_READ, so the same code can behave differently between them. Set a level on one method with @Transactional(isolation = Isolation.SERIALIZABLE) when an invariant needs it, and expect the database to abort some transactions under contention. Code that uses SERIALIZABLE must be ready to retry on a serialization failure.

Propagation in a table

Propagation says what happens when a transactional method is called from another. The default joins the caller's transaction:

PropagationBehaviour
REQUIREDJoin the current transaction, or start one
REQUIRES_NEWSuspend the current one and start a new one
SUPPORTSJoin if there is one, otherwise run without
NOT_SUPPORTEDSuspend the current one and run without
MANDATORYFail if there is no transaction
NEVERFail if there is a transaction
NESTEDA savepoint inside the current transaction

MANDATORY is useful on a method that must never be called outside a transaction, such as a repository helper, since it turns a silent bug into an immediate exception. REQUIRES_NEW costs a second connection while the first is held.

Do work after the commit, not before

Sending an email or publishing an event inside a transaction is a bug waiting for a rollback. The email goes out, then the transaction fails, and the customer is told about an order that does not exist. Hook the work to the commit:

java
@Service
class OrderService {

    private final ApplicationEventPublisher events;

    OrderService(ApplicationEventPublisher events) {
        this.events = events;
    }

    @Transactional
    public void place(Order order) {
        repository.save(order);
        events.publishEvent(new OrderPlaced(order.getId()));
    }
}

@Component
class OrderMailer {

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    void on(OrderPlaced event) {
        // runs only if the transaction committed
    }
}

The listener runs after a successful commit and not at all after a rollback. If the mail fails, the order is already saved, so make that step retryable, or write the message to an outbox table in the same transaction. A database write inside an AFTER_COMMIT listener needs REQUIRES_NEW, since the original transaction is finished.

Tests that roll back hide commit problems

A test method annotated @Transactional rolls back at the end, which keeps the database clean and also hides anything that happens at commit time: deferred constraints, flush errors and AFTER_COMMIT listeners. A test of a service method that expects a unique constraint to fail will pass or fail depending on whether the flush happens before the rollback. Call flush() in the test to force the statements, and for commit behaviour use a test without the annotation that cleans up explicitly, or @Commit on that one method.

java
@Test
void duplicateOrderNumberIsRejected() {
    service.place(orderWithNumber("A-1"));
    assertThrows(DataIntegrityViolationException.class, () -> {
        service.place(orderWithNumber("A-1"));
        entityManager.flush();
    });
}

Timeouts and read-only

A transaction can carry a timeout, @Transactional(timeout = 5), in seconds. It limits how long a statement may wait for the database, and it does not interrupt code that is not waiting on the database. A service method that loops in Java for ten minutes is not stopped by it. A readOnly = true hint lets Hibernate skip dirty checking and some drivers route the query to a replica, and it does not forbid writes on every database.

When this does not apply

Reading from a single table without the need for consistency may not need an explicit transaction. References: Spring transaction management and the Transactional Javadoc.

Also inHibernate
Taggedexplainer
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.