✅ How Rollback Works in Spring Boot?
🔄 Spring uses:
-
@Transactional
annotation - AOP (Aspect-Oriented Programming)
- Underlying transaction manager (e.g., JDBC, JPA, Hibernate)
🧪 Example: Rollback with @Transactional
👉 What Happens:
If the exception is thrown, all DB operations in the method are rolled back.
📌 By Default:
Spring rolls back only on unchecked exceptions (i.e., RuntimeException
and its subclasses).
🔧 Rollback on Checked Exceptions
🛠️ Common Use Cases for Rollback
Use Case | Rollback Used? |
---|---|
Multiple DB updates | ✅ Yes |
DB + external API call | ✅ Often yes |
Retry scenarios | ✅ With AOP |
Failed payment or transfer logic | ✅ Absolutely |
🚨 Tips
- Always annotate service layer, not repository or controller.
- Use
@Transactional(readOnly = true)
for read-only operations (optimization). - Don’t use
@Transactional
on private methods – it won’t work.