✅ 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

@Service
public class AccountService {

    @Autowired
    private AccountRepository accountRepo;

    @Transactional
    public void transferMoney(Long fromId, Long toId, double amount) {
        Account from = accountRepo.findById(fromId).orElseThrow();
        Account to = accountRepo.findById(toId).orElseThrow();

        from.setBalance(from.getBalance() - amount);
        to.setBalance(to.getBalance() + amount);

        accountRepo.save(from);

        if (amount > 10000) {
            throw new RuntimeException("Amount too large, rollback!");
        }

        accountRepo.save(to);
    }
}

👉 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

@Transactional(rollbackFor = Exception.class)
public void updateData() throws Exception {
    // code that might throw a checked exception
}


🛠️ 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.
Back to blog

Leave a comment