Skip to content
Commitwise
Menu

Why does @Transactional sometimes not work in Spring?

BackendSenior

In short@Transactional is applied by a proxy, so it only works on calls that go through the proxy: public methods called from another bean. Self-invocation, private methods and objects Spring didn't create skip it, and by default only unchecked exceptions roll back.

Model answer

Spring implements @Transactional with a proxy around the bean. The proxy starts a transaction, calls the real method, then commits or rolls back. Everything that bypasses the proxy bypasses the transaction:

  • Self-invocation: this.save() from inside the same bean calls the target directly. @Transactional(propagation = REQUIRES_NEW) on save does nothing in that case. Move the method to another bean, or inject the bean’s own proxy.
  • Visibility: proxies intercept public methods (protected and package-private only with class-based proxies in recent versions); private methods never.
  • Not a Spring bean: an object created with new has no proxy.

Rollback rules: by default only RuntimeException and Error roll back. A checked exception commits whatever was done. Use rollbackFor = Exception.class or throw unchecked exceptions from the service layer.

Propagation: REQUIRED (default) joins an existing transaction; REQUIRES_NEW suspends it and starts another (useful for audit logs that must persist even if the outer work fails, at the cost of a second connection). An inner REQUIRED method that throws marks the shared transaction rollback-only, so catching the exception outside still ends in UnexpectedRollbackException.

Design: put boundaries on service methods that represent one business operation, keep them short, never wrap remote HTTP calls or message publishing inside them (use the transactional outbox), and use readOnly = true for queries so the provider can skip dirty checking.

What they're looking for

The proxy mechanism, self-invocation, rollback rules for checked exceptions, propagation (REQUIRED vs REQUIRES_NEW), readOnly, and where transaction boundaries belong.

Common mistakes

  • Calling a @Transactional method from another method of the same class and expecting a new transaction.
  • Expecting a checked exception to roll back by default.
  • Long transactions around remote calls.

More backend questions

Esc

Type to search the whole site.