📖 Transaction: a group of operations that is all or nothing (ACID). @Transactional on a method makes Spring begin, commit or roll back the transaction. By default it rolls back on RuntimeException (use rollbackFor for checked ones).
| Annotation | Use |
|---|
@Transactional | Runs the method in one transaction |
@ExceptionHandler | Method that handles a given exception |
@ControllerAdvice | One class that handles exceptions for all controllers |
| Custom error response | A JSON body with status, error and message through ResponseEntity |
@Entity
public class Account {
@Id private Long id;
private String holder;
private double balance;
// getters and setters
}
public interface AccountRepository extends JpaRepository<Account, Long> { }
public class InsufficientFundsException extends RuntimeException {
public InsufficientFundsException(String m) { super(m); }
}
@Service
public class BankService {
private final AccountRepository repo;
public BankService(AccountRepository repo) { this.repo = repo; }
@Transactional // both updates commit together, or both roll back
public void transfer(Long fromId, Long toId, double amount) {
Account from = repo.findById(fromId).orElseThrow(() -> new IllegalArgumentException("No account " + fromId));
Account to = repo.findById(toId).orElseThrow(() -> new IllegalArgumentException("No account " + toId));
if (from.getBalance() < amount) throw new InsufficientFundsException("Balance too low");
from.setBalance(from.getBalance() - amount); // debit
to.setBalance(to.getBalance() + amount); // credit
}
}
@RestController
@RequestMapping("/bank")
public class BankController {
private final BankService service;
public BankController(BankService service) { this.service = service; }
@PostMapping("/transfer")
public String transfer(@RequestBody TransferRequest r) {
service.transfer(r.from(), r.to(), r.amount());
return "Transfer successful";
}
}
record TransferRequest(Long from, Long to, double amount) { }
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(InsufficientFundsException.class)
public ResponseEntity<Map<String, Object>> handle(InsufficientFundsException ex) {
Map<String, Object> body = Map.of("status", 400, "error", "Bad Request", "message", ex.getMessage());
return ResponseEntity.badRequest().body(body);
}
}
// Response when balance is too low (expected)
HTTP 400
{"status":400,"error":"Bad Request","message":"Balance too low"}
Common mistake: @Transactional does not work when a method calls another method of the same class (the proxy is bypassed), or on private methods.