@Transactional: Database Transactions Explained
Your money is safe — transactions ensure all steps succeed or none do.
A transaction is a group of database operations that must either all succeed together, or all fail together. If one fails, the whole group is rolled back. This is crucial for financial apps or any app with multiple related tables.
The Hyderabad Bank Transfer Analogy:
Imagine you are at SBI Bank in Hyderabad. You want to transfer ₹500 from your account to your friend's account. This is two steps:
- Deduct ₹500 from your account.
- Add ₹500 to your friend's account.
If the bank server crashes exactly after step 1, your money is gone! To prevent this, banks wrap both steps in a Transaction. If step 2 fails, step 1 is "rolled back" (undone). Your money stays safe. It's all or nothing.
In Spring Boot, we use the @Transactional annotation to wrap methods in this all-or-nothing safety bubble.
- @Transactional: When placed on a method, Spring intercepts the method call. It starts a database session and transaction before the method runs.
- Commit: If the method finishes successfully, Spring tells the database to commit (save) all changes.
- Rollback: If the method throws an unchecked
RuntimeException, Spring tells the database to rollback (undo) all changes made during that method.
package com.devinhyderabad;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Service
class BankService {
// Wrapping this in a transaction means ALL database changes inside
// will only save if the method completes without crashing.
@Transactional
public String transferMoney(Long fromId, Long toId, int amount) {
// 1. Deduct money (Imagine this is a DB update)
System.out.println("Deducting " + amount + " from Account " + fromId);
// 2. Add money (Imagine this is a DB update)
System.out.println("Adding " + amount + " to Account " + toId);
// 3. Simulate a crash!
if (true) {
throw new RuntimeException("Server crashed before adding money!");
}
// This line never runs
return "Transfer successful";
}
}@RestController
@RequestMapping("/api/bank")
class BankController {
private final BankService bankService;
public BankController(BankService bankService) { this.bankService = bankService; }
@PostMapping("/transfer")
public String transfer(@RequestParam Long from, @RequestParam Long to, @RequestParam int amount) {
try {
return bankService.transferMoney(from, to, amount);
} catch (Exception e) {
return "Transfer failed! Money safely rolled back.";
}
}
}Because of @Transactional, when the RuntimeException is thrown, any DB changes made before the crash are undone.
Interview Question: "What is @Transactional and what is its rollback behavior?"
Answer: @Transactional creates a database transaction scope. By default, Spring only rolls back the transaction if an unchecked exception (a RuntimeException or Error) is thrown. If a checked exception (like IOException) is thrown, Spring will commit the transaction unless you explicitly specify @Transactional(rollbackFor = Exception.class).
Enterprise Note: Always put @Transactional on your @Service layer methods, never on your @Repository or @Controller. The service layer is where business logic spans multiple repository calls, ensuring the whole business operation is atomic.
Key Takeaways
- ✅ @Transactional ensures all-or-nothing execution of database operations
- ✅ Rollback happens automatically on RuntimeException (unchecked exceptions)
- ✅ Checked exceptions do NOT trigger rollback — use rollbackFor = Exception.class
- ✅ Always annotate @Service layer methods, never @Controller or @Repository
Want to track your progress?
Log in to save your place and pick up where you left off.
Progress track karna chahte ho?
Login karo apni progress save karne ke liye aur jahan chhoda tha wahan se shuru karo.
Login