Skip to content
javahacks.dev
Spring Framework

Fix Transactional Not Working on Self Called Methods

Find out why @Transactional is ignored on a self call, a private method or a swallowed exception, and fix it by moving the call across a bean boundary.

6 min read
Summarize in AI
Flat illustration of a Spring container wiring beans together, with the Spring, Spring Boot, Hibernate and JUnit5 logos.

The annotation is present, the method runs and the transaction does not do what it says. Five causes cover nearly all of it, and the first is the one everyone meets. The proxy model behind it is explained in how the Spring container works.

Check whether a transaction exists

Do not infer it from behavior. Ask Spring:

java
@Transactional
public void save(Invoice invoice) {
    System.out.println("active = " + TransactionSynchronizationManager.isActualTransactionActive());
}

It prints active = true when the call went through the proxy and false when it did not. Put the line in the method you suspect and call it the way production does.

Cause 1: self-invocation

java
@Service
class InvoiceService {

    public void importAll(List<Invoice> invoices) {
        for (Invoice i : invoices) {
            save(i);                 // plain call on this: no proxy, no transaction
        }
    }

    @Transactional
    public void save(Invoice invoice) { repository.save(invoice); }
}

The caller of importAll holds a proxy, but inside the class this is the raw object. Annotations on save are never consulted. Extract it:

java
@Service
class InvoiceWriter {
    @Transactional
    public void save(Invoice invoice) { repository.save(invoice); }
}

@Service
class InvoiceService {
    private final InvoiceWriter writer;
    InvoiceService(InvoiceWriter writer) { this.writer = writer; }

    public void importAll(List<Invoice> invoices) {
        invoices.forEach(writer::save);      // each call is its own transaction
    }
}

Now the transaction boundary is visible in the class structure. If you want one transaction around the whole import, annotate importAll instead. Injecting the bean into itself, or enabling AspectJ weaving, also works, and both are more machinery than a second class.

Cause 2: the exception is a checked one

By default Spring rolls back on RuntimeException and Error only. A method that throws IOException commits:

java
@Transactional(rollbackFor = Exception.class)
public void importFile(Path path) throws IOException { /* ... */ }

Setting rollbackFor to Exception.class gives the behavior most people expect.

Cause 3: the exception was swallowed

java
@Transactional
public void save(Invoice invoice) {
    try {
        repository.save(invoice);
    } catch (DataIntegrityViolationException e) {
        log.warn("duplicate", e);          // transaction is marked rollback-only or half-done
    }
}

If the exception never leaves the method, the proxy sees a normal return and commits what it can. If a nested transactional call already marked the transaction rollback-only, you get UnexpectedRollbackException at commit. Rethrow, or restructure so the catch sits outside the transaction boundary.

Cause 4: the method or the class cannot be proxied

A private method is invisible to the proxy. A final class cannot be subclassed for CGLIB proxies. Methods must be visible to the proxy; Spring Framework 6 and later can proxy protected and package-private methods on class-based proxies, but public is the safe choice. An object created with new InvoiceService() is not a Spring bean and has no proxy at all.

Cause 5: another thread

A transaction is bound to the thread that started it. Work submitted to an executor or an @Async method runs in another thread with no transaction, even inside a transactional method. Start a transaction inside the task.

Summary table

SymptomCheck
Nothing is transactionalSelf call or private method
Data committed despite an errorChecked exception or caught exception
TransactionRequiredExceptionMissing transaction
Lazy loading works in one entry point, not anotherWhich method starts the transaction

Turn on transaction logging

When the cause is not obvious from the code, the framework can describe each decision. Two loggers show it:

properties
logging.level.org.springframework.transaction.interceptor=TRACE
logging.level.org.springframework.orm.jpa.JpaTransactionManager=DEBUG

A call that went through the proxy prints lines like Getting transaction for [dev.javahacks.shop.InvoiceWriter.save] and Completing transaction, followed by the commit or the rollback. A call that did not go through the proxy prints nothing for that method. Count the pairs against the calls you expected, and a missing pair identifies the self-invocation without reading any other code.

Where the annotation goes

Put @Transactional on the concrete class or its public methods. It also works on an interface, but only for interface-based JDK proxies, and Spring Boot defaults to class-based proxies, so an annotation placed only on an interface method may be ignored. The safe rule is the class. Use the Spring annotation, org.springframework.transaction.annotation.Transactional, or the Jakarta one, jakarta.transaction.Transactional. Both are supported, and they differ in attributes: the Jakarta one uses rollbackOn and dontRollbackOn, not rollbackFor. Mixing the two between files in one project produces transactions that roll back differently for the same exception.

Propagation decides what an inner call does

An inner transactional method joins the existing transaction by default (REQUIRED). That is the right default, and it is also why a failure inside the inner method can poison the outer one. Use REQUIRES_NEW when the inner work must commit whatever happens outside, such as an audit record:

java
@Service
class AuditWriter {

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void record(String event) {
        auditRepository.save(new AuditEntry(event));
    }
}

The inner transaction suspends the outer one, uses a second connection, and commits independently. The cost is one more connection held at the same time, so a pool of 10 with 10 threads in the outer method deadlocks waiting for the inner connection. Size the pool with that in mind, or avoid REQUIRES_NEW inside loops.

readOnly is a hint, not a lock

@Transactional(readOnly = true) tells Hibernate to skip dirty checking and may tell the driver to route the connection to a replica. It does not stop a write on every database. Some drivers accept the write silently, so a bug can persist data inside a method that is marked read-only. Keep write methods separate from read methods, and test with the same database engine as production rather than an embedded one.

When there are two transaction managers

An application with two data sources has two PlatformTransactionManager beans, and @Transactional without a name picks the primary one. A write to the second database then runs with no transaction of its own.

java
@Transactional("ordersTransactionManager")
public void saveOrder(Order order) { ordersRepository.save(order); }

Name the manager on every method that touches the non-primary source. A test that checks TransactionSynchronizationManager.getCurrentTransactionName() shows which one is active.

The programmatic version

When the boundary needs to sit inside a method, or the class cannot be split, TransactionTemplate states it in code and never depends on a proxy:

java
@Service
class InvoiceService {

    private final TransactionTemplate tx;

    InvoiceService(PlatformTransactionManager manager) {
        this.tx = new TransactionTemplate(manager);
    }

    public void importAll(List<Invoice> invoices) {
        for (Invoice invoice : invoices) {
            tx.executeWithoutResult(status -> repository.save(invoice));
        }
    }
}

Each iteration gets its own transaction, which is what the original importAll was trying to express. It also makes the batch size a visible number. Committing every 500 rows is a decision with a cost in memory and in the length of a lock, and it deserves to be written in the code where a reader can change it.

Where this does not apply

If you must keep a single class, use TransactionTemplate explicitly. If the database does not support transactions on the table, as with MySQL's MyISAM engine, no Spring setting helps; use InnoDB. The Spring transaction reference lists the annotation's attributes. A related failure with the same root is [TransactionRequiredException](/library/transactionrequiredexception-fix-spring-jpa), and the guide to Hibernate and JPA shows what a missing transaction does to lazy loading. The Spring Framework API documentation documents the behavior in detail.

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.