Video in progress

Strong Middle 🌱 Spring

Why doesn't a @Transactional (or @Cacheable, @Async) method work when it is called from within the same class?

Because these annotations work through a proxy. A call from outside goes through the proxy, but inside the class this.method() goes straight to the real object. The proxy is bypassed and the annotation does nothing.

📖 Answer

@Service
public class ImportService {
    public void importAll(List<Row> rows) {
        for (Row r : rows) {
            importOne(r);           // this.importOne, not the proxy
        }
    }

    @Transactional(propagation = REQUIRES_NEW)
    public void importOne(Row r) { ... } // each row was supposed to get its own transaction
}

Diagram:

Controller → [proxy] → ImportService.importAll → this.importOne (no proxy)

Fixes, best first:

  1. Move the method to another bean, say RowImporter.importOne. The design usually gets cleaner too.
  2. Manage the transaction by hand with TransactionTemplate:
    rows.forEach(r -> tx.executeWithoutResult(s -> importOne(r)));
    
  3. Inject the proxy into itself (@Lazy ImportService self). It works, but the code gets confusing.
  4. AspectJ weaving (changing bytecode instead of using a proxy). Rarely needed.

The worst part is that it fails silently. There is no error; the transaction just doesn't behave the way you think. That's why it's worth checking transaction boundaries with an integration test.