Video in progress

Why isn't `@Transactional` working in this code? Which pattern is it related to?

@Service
public class ImportService {

    public void importFile(Path file) {
        var rows = parse(file);
        saveAll(rows);          // no transaction!
    }

    @Transactional
    public void saveAll(List<Row> rows) {
        rows.forEach(repo::save);
    }
}

@Transactional works through a Spring proxy. The call this.saveAll() bypasses the proxy and goes straight to the object itself, so no transaction is opened. This is a natural limitation of the Proxy pattern.

📖 Answer

When Spring creates the ImportService bean, it hands other beans not the real object but its proxy. When the controller calls importService.importFile(...), the call arrives at the proxy; importFile has no annotation, so the proxy just passes it on to the real object. Inside the real object, saveAll(rows) is this.saveAll(rows), and this is not the proxy. As a result every save runs in its own separate transaction, and if there's an error, half of the rows stay saved.

It's easy to check: log TransactionSynchronizationManager.isActualTransactionActive() inside saveAll, and you'll see false.

Ways to fix it:

  1. Move @Transactional to the outer method that gets called (importFile): often the most correct choice.
  2. Extract saveAll into a separate bean (RowWriter): the call now goes through the proxy.
  3. Manage it by hand with TransactionTemplate.

Injecting the bean into itself (@Lazy ImportService self) also works, but it hides a design problem, and I don't recommend it.

The same problem exists with @Async, @Cacheable and @Retryable, since they all rely on the proxy. An annotation put on a private method is ignored for the same reason.