How @Transactional Works Internally, and Rollback Exception Rules
How @Transactional Works Internally
Section titled “How @Transactional Works Internally”Spring implements @Transactional using Spring AOP and proxy objects.
flowchart LR
A[Client] --> B[Spring Proxy]
B --> C[Begin Transaction]
C --> D[Execute Target Method]
D --> E{Exception?}
E -- No --> F[Commit]
E -- Yes --> G[Rollback]
Internal Components
Section titled “Internal Components”PlatformTransactionManagerTransactionInterceptor- Spring AOP Proxy
Example:
@Transactionalpublic void createOrder(Order order) { orderRepository.save(order);}Conceptually:
transactionManager.begin()method executiontransactionManager.commit()or rollback on failure.
Exception Handling and Rollback Rules
Section titled “Exception Handling and Rollback Rules”By default, Spring rolls back transactions only for:
RuntimeExceptionError
| Exception Type | Rollback |
|---|---|
| RuntimeException | Yes |
| Checked Exception | No |
Example:
@Transactionalpublic void processPayment() { throw new RuntimeException();}To roll back on checked exceptions:
@Transactional(rollbackFor = Exception.class)or
@Transactional(rollbackFor = SQLException.class)Key Takeaways
Section titled “Key Takeaways”@Transactionalworks through a Spring AOP proxy:TransactionInterceptorwraps the call, delegating begin/commit/rollback toPlatformTransactionManager.- By default, only unchecked exceptions (
RuntimeException/Error) trigger a rollback — a checked exception likeSQLExceptionwill NOT roll back the transaction unlessrollbackForis set explicitly. - Since the mechanism is proxy-based, this only applies to calls that pass through the proxy — self-invoked private/internal method calls silently skip transactional behavior.