Hackforge Academy

Category: java

How to implement rollback in spring boot db

Published on 04 May 2026

Explanation

In Spring Boot, rollback is implemented using transaction management with the @Transactional annotation. It ensures that all database operations within a method are executed as a single transaction and will be rolled back automatically if an exception occurs.

Code:

@Service
public class UserService {

    @Transactional
    public void transfer() {
        // DB operation 1
        // DB operation 2
        // if exception occurs -> 
rollback automatically
    }
}

Explanation

By default, Spring rolls back transactions only for unchecked exceptions (RuntimeException and Error). Checked exceptions do not trigger rollback unless explicitly configured.

Code:

@Transactional(rollbackFor = Exception.class)
public void process() throws Exception {
    // this will rollback for 
checked exceptions also
}

Explanation

Example: Implementing rollback in a money transfer scenario where failure in one operation should revert all changes.

Code:

@Service
public class BankService {

    @Autowired
    private AccountRepository repo;

    @Transactional
    public void transferMoney(int fromId,
 int toId, double amount) {
        repo.debit(fromId, amount);

        // simulate error
        if(true) throw new 
RuntimeException("Error occurred");

        repo.credit(toId, amount);
    }
}

Explanation

Rollback can also be triggered programmatically using TransactionAspectSupport if needed.

Code:

import org.springframework.
transaction.interceptor.
TransactionAspectSupport;

@Transactional
public void process() {
    try {
        // some logic
    } catch (Exception e) {
        TransactionAspectSupport.
currentTransactionStatus().
setRollbackOnly();
    }
}

Explanation

Real-time usage: Used in banking systems, order processing, and payment systems to ensure data consistency. If any step fails (like payment failure), all previous operations are rolled back automatically.

Code:

// Order service example
@Transactional
public void placeOrder() {
    saveOrder();
    processPayment();
    updateInventory();
    // if any fails -> rollback all
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community