Spring's @Transactional works through proxies: calls from outside the bean go through a proxy that starts, joins, commits or rolls back transactions. Propagation (most important types) - REQUIRED (default): join the existing transaction or create a new one. - REQUIRES_NEW: suspend the current transaction and start an independent one; it commits or rolls back on its own. Useful for audit logs that must persist even if the main transaction fails. - NESTED: a savepoint within the current transaction (JDBC savepoints); rolling back the nested part does not roll back the outer transaction. - SUPPORTS, NOT_SUPPORTED, MANDATORY, NEVER for special cases. Rollback rules - By default, Spring rolls back for unchecked exceptions (RuntimeException and Error), but not for checked exceptions. - Change with @Transactional(rollbackFor = Exception.class) or noRollbackFor. - Catching an exception inside the method and not rethrowing it means no rollback happens. Common proxy-related mistakes 1. Self-invocation: calling a @Transactional method from another method in the same class bypasses the proxy, so the annotation is ignored: public void placeOrder() { saveOrder(); } // not transactional via proxy @Transactional public void saveOrder() { ... } Fixes: move the method to another bean, inject the bean's own proxy, or use TransactionTemplate. 2. Non-public methods: with proxy-based AOP, annotations on private methods are ignored (Spring 6 supports protected and package-visible methods for class-based proxies, but public is safest). 3. "Transaction silently rolled back because it has been marked as rollback-only": an inner REQUIRED method threw a runtime exception (marking the shared transaction rollback-only), the outer method caught it and tried to commit, causing UnexpectedRollbackException. Fix: let the exception propagate, or use REQUIRES_NEW for work that may fail independently. 4. Checked exceptions not rolling back: a business exception extending Exception commits partial changes unless rollbackFor is set. 5. readOnly misunderstandings: readOnly = true is a hint (Hibernate skips dirty checking, and some drivers route to replicas); it does not prevent all writes. 6. Long transactions around remote calls: calling HTTP services inside a transaction holds database connections and locks. Do remote calls outside, and use the outbox pattern for messaging. 7. Async and new threads: transactions are bound to the thread; @Async methods do not share the caller's transaction. 8. Events after commit: use @TransactionalEventListener(phase = AFTER_COMMIT) to send emails or messages only after the transaction commits.
Ravindra Wadile · · 0 likes