TP2 - Transactions and Rollback
Objectives of the Lab
In this lab, you will:
- ✅ Create a money transfer system with transactions
- ✅ Observe the behavior of rollbacks
- ✅ Test different propagation levels
- ✅ Understand the self-invocation trap
- ✅ Use read-only transactions
Estimated duration: 1h30
Context
You are developing a simplified banking application. A money transfer must:
- Debit the source account
- Credit the destination account
- Log the operation in an audit
Golden rule: If one step fails, EVERYTHING must be rolled back!
Part 1: Project Setup
1.1 Resume Project TP7.1
Continue with the datasource-demo project from TP7.1, or create a new project with the same dependencies.
1.2 Structure
src/main/java/com/example/bank/
├── model/
│ ├── Account.java
│ └── TransactionLog.java
├── repository/
│ ├── AccountRepository.java
│ └── TransactionLogRepository.java
├── service/
│ ├── AccountService.java
│ ├── TransferService.java
│ └── AuditService.java
├── controller/
│ └── TransferController.java
└── exception/
└── InsufficientFundsException.java
Part 2: Entities
2.1 Account (Bank Account)
// src/main/java/com/example/bank/model/Account.java
package com.example.bank.model;
import jakarta.persistence.*;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
import java.math.BigDecimal;
@Entity
@Table(name = "accounts")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, nullable = false)
private String accountNumber;
@Column(nullable = false)
private String ownerName;
@Column(nullable = false, precision = 15, scale = 2)
private BigDecimal balance;
public Account(String accountNumber, String ownerName, BigDecimal balance) {
this.accountNumber = accountNumber;
this.ownerName = ownerName;
this.balance = balance;
}
public void debit(BigDecimal amount) {
if (this.balance.compareTo(amount) < 0) {
throw new IllegalStateException("Insufficient balance");
}
this.balance = this.balance.subtract(amount);
}
public void credit(BigDecimal amount) {
this.balance = this.balance.add(amount);
}
}
2.2 TransactionLog (Audit Log)
// src/main/java/com/example/bank/model/TransactionLog.java
package com.example.bank.model;
import jakarta.persistence.*;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Entity
@Table(name = "transaction_logs")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TransactionLog {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String fromAccount;
@Column(nullable = false)
private String toAccount;
@Column(nullable = false, precision = 15, scale = 2)
private BigDecimal amount;
@Column(nullable = false)
private String status; // SUCCESS, FAILED
private String errorMessage;
@Column(nullable = false)
private LocalDateTime timestamp = LocalDateTime.now();
public TransactionLog(String from, String to, BigDecimal amount, String status) {
this.fromAccount = from;
this.toAccount = to;
this.amount = amount;
this.status = status;
this.timestamp = LocalDateTime.now();
}
}
2.3 Custom Exception
// src/main/java/com/example/bank/exception/InsufficientFundsException.java
package com.example.bank.exception;
public class InsufficientFundsException extends RuntimeException {
public InsufficientFundsException(String message) {
super(message);
}
}
Part 3: Repositories
// AccountRepository.java
package com.example.bank.repository;
import com.example.bank.model.Account;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface AccountRepository extends JpaRepository<Account, Long> {
Optional<Account> findByAccountNumber(String accountNumber);
}
// TransactionLogRepository.java
package com.example.bank.repository;
import com.example.bank.model.TransactionLog;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface TransactionLogRepository extends JpaRepository<TransactionLog, Long> {
List<TransactionLog> findByFromAccountOrToAccount(String from, String to);
}
Part 4: Services
4.1 AccountService
// src/main/java/com/example/bank/service/AccountService.java
package com.example.bank.service;
import com.example.bank.exception.InsufficientFundsException;
import com.example.bank.model.Account;
import com.example.bank.repository.AccountRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.List;
@Service
@RequiredArgsConstructor
@Slf4j
public class AccountService {
private final AccountRepository accountRepository;
@Transactional(readOnly = true)
public List<Account> getAllAccounts() {
return accountRepository.findAll();
}
@Transactional(readOnly = true)
public Account getAccount(String accountNumber) {
return accountRepository.findByAccountNumber(accountNumber)
.orElseThrow(() -> new RuntimeException("Account not found: " + accountNumber));
}
@Transactional
public void debit(String accountNumber, BigDecimal amount) {
log.info("Debiting {} from account {}", amount, accountNumber);
Account account = getAccount(accountNumber);
if (account.getBalance().compareTo(amount) < 0) {
throw new InsufficientFundsException(
"Insufficient balance. Available: " + account.getBalance() + ", Requested: " + amount
);
}
account.debit(amount);
accountRepository.save(account);
log.info("Debit successful. New balance: {}", account.getBalance());
}
@Transactional
public void credit(String accountNumber, BigDecimal amount) {
log.info("Crediting {} to account {}", amount, accountNumber);
Account account = getAccount(accountNumber);
account.credit(amount);
accountRepository.save(account);
log.info("Credit successful. New balance: {}", account.getBalance());
}
@Transactional
public Account createAccount(String accountNumber, String ownerName, BigDecimal initialBalance) {
Account account = new Account(accountNumber, ownerName, initialBalance);
return accountRepository.save(account);
}
}
4.2 AuditService (With REQUIRES_NEW)
// src/main/java/com/example/bank/service/AuditService.java
package com.example.bank.service;
import com.example.bank.model.TransactionLog;
import com.example.bank.repository.TransactionLogRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.List;
@Service
@RequiredArgsConstructor
@Slf4j
public class AuditService {
private final TransactionLogRepository logRepository;
/**
* Log in a NEW transaction.
* Even if the main transaction fails, the log is preserved!
*/
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void logTransaction(String from, String to, BigDecimal amount,
String status, String errorMessage) {
log.info("Logging transaction: {} -> {} ({}€) - Status: {}",
from, to, amount, status);
TransactionLog txLog = new TransactionLog(from, to, amount, status);
txLog.setErrorMessage(errorMessage);
logRepository.save(txLog);
log.info("Transaction log saved with ID: {}", txLog.getId());
}
@Transactional(readOnly = true)
public List<TransactionLog> getLogsForAccount(String accountNumber) {
return logRepository.findByFromAccountOrToAccount(accountNumber, accountNumber);
}
@Transactional(readOnly = true)
public List<TransactionLog> getAllLogs() {
return logRepository.findAll();
}
}
4.3 TransferService (The Main Service)
// src/main/java/com/example/bank/service/TransferService.java
package com.example.bank.service;
import com.example.bank.exception.InsufficientFundsException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
@Service
@RequiredArgsConstructor
@Slf4j
public class TransferService {
private final AccountService accountService;
private final AuditService auditService;
/**
* Money transfer WITH transaction.
* If one step fails, everything is rolled back (except the audit log).
*/
@Transactional
public void transfer(String fromAccount, String toAccount, BigDecimal amount) {
log.info("=== Starting transfer: {} -> {} ({}€) ===", fromAccount, toAccount, amount);
try {
// Step 1: Debit the source account
accountService.debit(fromAccount, amount);
// Simulate an error (uncomment to test rollback)
// if (amount.compareTo(new BigDecimal("100")) > 0) {
// throw new RuntimeException("Simulated error!");
// }
// Step 2: Credit the destination account
accountService.credit(toAccount, amount);
// Step 3: Log success (REQUIRES_NEW = separate transaction)
auditService.logTransaction(fromAccount, toAccount, amount, "SUCCESS", null);
log.info("=== Transfer successful! ===");
} catch (InsufficientFundsException e) {
// Log failure (even if the main transaction is rolling back)
auditService.logTransaction(fromAccount, toAccount, amount, "FAILED", e.getMessage());
throw e;
} catch (Exception e) {
// Log failure
auditService.logTransaction(fromAccount, toAccount, amount, "FAILED", e.getMessage());
throw new RuntimeException("Error during transfer: " + e.getMessage(), e);
}
}
/**
* Version WITHOUT transaction (for demonstration).
* DO NOT USE IN PRODUCTION!
*/
public void transferNoTransaction(String fromAccount, String toAccount, BigDecimal amount) {
log.warn("⚠️ Transfer WITHOUT transaction - DANGEROUS!");
// Debit
accountService.debit(fromAccount, amount);
// Simulate an error after debit
throw new RuntimeException("Error after debit!");
// Credit will never be executed
// accountService.credit(toAccount, amount);
}
}
Part 5: Controller and Test Data
5.1 TransferController
// src/main/java/com/example/bank/controller/TransferController.java
package com.example.bank.controller;
import com.example.bank.model.Account;
import com.example.bank.model.TransactionLog;
import com.example.bank.service.AccountService;
import com.example.bank.service.AuditService;
import com.example.bank.service.TransferService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/bank")
@RequiredArgsConstructor
public class TransferController {
private final AccountService accountService;
private final TransferService transferService;
private final AuditService auditService;
// === ACCOUNTS ===
@GetMapping("/accounts")
public List<Account> getAllAccounts() {
return accountService.getAllAccounts();
}
@GetMapping("/accounts/{accountNumber}")
public Account getAccount(@PathVariable String accountNumber) {
return accountService.getAccount(accountNumber);
}
// === TRANSFERS ===
@PostMapping("/transfer")
public ResponseEntity<String> transfer(@RequestBody Map<String, Object> request) {
String from = (String) request.get("from");
String to = (String) request.get("to");
BigDecimal amount = new BigDecimal(request.get("amount").toString());
transferService.transfer(from, to, amount);
return ResponseEntity.ok("Transfer successful!");
}
@PostMapping("/transfer-no-tx")
public ResponseEntity<String> transferNoTransaction(@RequestBody Map<String, Object> request) {
String from = (String) request.get("from");
String to = (String) request.get("to");
BigDecimal amount = new BigDecimal(request.get("amount").toString());
transferService.transferNoTransaction(from, to, amount);
return ResponseEntity.ok("Transfer successful!");
}
// === AUDIT ===
@GetMapping("/logs")
public List<TransactionLog> getAllLogs() {
return auditService.getAllLogs();
}
@GetMapping("/logs/{accountNumber}")
public List<TransactionLog> getAccountLogs(@PathVariable String accountNumber) {
return auditService.getLogsForAccount(accountNumber);
}
}
5.2 Initial Data
-- src/main/resources/data.sql
INSERT INTO accounts (account_number, owner_name, balance) VALUES
('ACC001', 'Alice Martin', 1000.00),
('ACC002', 'Bob Dupont', 500.00),
('ACC003', 'Charlie Bernard', 2500.00);
5.3 Configuration
# application-dev.properties (add)
spring.jpa.defer-datasource-initialization=true
spring.sql.init.mode=always
Part 6: Practical Tests
6.1 Test 1: Successful Transfer
# Check initial balances
curl http://localhost:8080/api/bank/accounts
# Transfer 200€ from ACC001 to ACC002
curl -X POST http://localhost:8080/api/bank/transfer \
-H "Content-Type: application/json" \
-d '{"from":"ACC001", "to":"ACC002", "amount":200}'
# Check new balances
curl http://localhost:8080/api/bank/accounts
# Check logs
curl http://localhost:8080/api/bank/logs
Expected result:
- ACC001: 1000 → 800€
- ACC002: 500 → 700€
- Log with status "SUCCESS"
6.2 Test 2: Insufficient Balance (Rollback)
# Attempt a transfer of 2000€ (ACC001 only has 800€)
curl -X POST http://localhost:8080/api/bank/transfer \
-H "Content-Type: application/json" \
-d '{"from":"ACC001", "to":"ACC002", "amount":2000}'
# Verify that balances have NOT changed
curl http://localhost:8080/api/bank/accounts
# Verify that the failure log is present!
curl http://localhost:8080/api/bank/logs
Expected result:
- ACC001: remains 800€ (no change)
- ACC002: remains 700€ (no change)
- Log with status "FAILED" and error message
6.3 Test 3: Without Transaction (DANGEROUS)
# Restart the application to reset data
# Try the transfer without transaction
curl -X POST http://localhost:8080/api/bank/transfer-no-tx \
-H "Content-Type: application/json" \
-d '{"from":"ACC001", "to":"ACC002", "amount":200}'
# Check balances
curl http://localhost:8080/api/bank/accounts
Expected result (BUG!):
- ACC001: 1000 → 800€ (debited!)
- ACC002: remains 500€ (never credited!)
- 200€ have disappeared! 💀
Part 7: Understanding REQUIRES_NEW
7.1 Why is the Audit Log Preserved?
Look at this diagram:
7.2 Exercise: Modify the Behavior
- In
AuditService, changeREQUIRES_NEWtoREQUIRED - Rerun test 2 (insufficient balance)
- Observe: the log is no longer created in case of failure!
// Try this temporarily:
@Transactional(propagation = Propagation.REQUIRED) // Instead of REQUIRES_NEW
public void logTransaction(...) { }
Part 8: The Self-Invocation Trap
8.1 The Problem
Add this method in TransferService:
// Method with the self-invocation trap
public void transferWithLogging(String from, String to, BigDecimal amount) {
log.info("External call...");
// ⚠️ TRAP: Direct call = no proxy = no transaction!
this.transfer(from, to, amount); // @Transactional ignored!
}
8.2 The Solution
@Service
@RequiredArgsConstructor
@Slf4j
public class TransferService {
private final AccountService accountService;
private final AuditService auditService;
// Injecting self to go through the proxy
@Autowired
private TransferService self;
public void transferWithLogging(String from, String to, BigDecimal amount) {
log.info("External call...");
// ✅ Goes through the proxy = active transaction!
self.transfer(from, to, amount);
}
@Transactional
public void transfer(String from, String to, BigDecimal amount) {
// ... existing code
}
}
Part 9: ReadOnly Transaction
9.1 Check Optimization
Add logging in AccountService:
@Transactional(readOnly = true)
public List<Account> getAllAccounts() {
log.info("Transaction readOnly = true");
List<Account> accounts = accountRepository.findAll();
// This will NOT be persisted because readOnly = true
accounts.forEach(a -> a.setBalance(BigDecimal.ZERO));
return accounts;
}
Test:
curl http://localhost:8080/api/bank/accounts
# Displayed balances are 0...
curl http://localhost:8080/api/bank/accounts
# But the real balances are unchanged!
Summary
What You Have Learned
| Concept | Example |
|---|---|
| @Transactional | Ensures atomicity |
| Rollback | Rolls back everything in case of error |
| REQUIRES_NEW | Independent transaction |
| readOnly | Optimization for reads |
| Self-invocation | Spring proxy trap |
Golden Rules
1. Always use @Transactional on write operations
2. Use REQUIRES_NEW for audit logs
3. Avoid self-invocation
4. Use readOnly = true for reads
5. Never swallow exceptions
🎯 Next Step
➡️ TP7.3: Migration with Flyway