TP2 - Transactions et Rollback
Objectifs du TP
Dans ce TP, vous allez:
- ✅ Créer un système de transfert d'argent avec transactions
- ✅ Observer le comportement des rollbacks
- ✅ Tester les différents niveaux de propagation
- ✅ Comprendre le piège de la self-invocation
- ✅ Utiliser les transactions en lecture seule
Durée estimée: 1h30
Contexte
Vous développez une application bancaire simplifiée. Un transfert d'argent doit:
- Débiter le compte source
- Créditer le compte destination
- Logger l'opération dans un audit
Règle d'or: Si une étape échoue, TOUT doit être annulé!
Partie 1: Setup du Projet
1.1 Reprendre le Projet TP7.1
Continuez avec le projet datasource-demo du TP7.1, ou créez un nouveau projet avec les mêmes dépendances.
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
Partie 2: Les Entités
2.1 Account (Compte Bancaire)
// 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("Solde insuffisant");
}
this.balance = this.balance.subtract(amount);
}
public void credit(BigDecimal amount) {
this.balance = this.balance.add(amount);
}
}
2.2 TransactionLog (Journal d'Audit)
// 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 Exception Personnalisée
// 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);
}
}
Partie 3: Les 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);
}
Partie 4: Les 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("Compte non trouvé: " + accountNumber));
}
@Transactional
public void debit(String accountNumber, BigDecimal amount) {
log.info("Débit de {} sur le compte {}", amount, accountNumber);
Account account = getAccount(accountNumber);
if (account.getBalance().compareTo(amount) < 0) {
throw new InsufficientFundsException(
"Solde insuffisant. Disponible: " + account.getBalance() + ", Demandé: " + amount
);
}
account.debit(amount);
accountRepository.save(account);
log.info("Débit effectué. Nouveau solde: {}", account.getBalance());
}
@Transactional
public void credit(String accountNumber, BigDecimal amount) {
log.info("Crédit de {} sur le compte {}", amount, accountNumber);
Account account = getAccount(accountNumber);
account.credit(amount);
accountRepository.save(account);
log.info("Crédit effectué. Nouveau solde: {}", 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 (Avec 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 dans une NOUVELLE transaction.
* Même si la transaction principale échoue, le log est conservé!
*/
@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 (Le Service Principal)
// 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;
/**
* Transfert d'argent AVEC transaction.
* Si une étape échoue, tout est annulé (sauf le log d'audit).
*/
@Transactional
public void transfer(String fromAccount, String toAccount, BigDecimal amount) {
log.info("=== Début transfert: {} -> {} ({}€) ===", fromAccount, toAccount, amount);
try {
// Étape 1: Débiter le compte source
accountService.debit(fromAccount, amount);
// Simuler une erreur (décommenter pour tester le rollback)
// if (amount.compareTo(new BigDecimal("100")) > 0) {
// throw new RuntimeException("Erreur simulée!");
// }
// Étape 2: Créditer le compte destination
accountService.credit(toAccount, amount);
// Étape 3: Logger le succès (REQUIRES_NEW = transaction séparée)
auditService.logTransaction(fromAccount, toAccount, amount, "SUCCESS", null);
log.info("=== Transfert réussi! ===");
} catch (InsufficientFundsException e) {
// Logger l'échec (même si la transaction principale est en rollback)
auditService.logTransaction(fromAccount, toAccount, amount, "FAILED", e.getMessage());
throw e;
} catch (Exception e) {
// Logger l'échec
auditService.logTransaction(fromAccount, toAccount, amount, "FAILED", e.getMessage());
throw new RuntimeException("Erreur lors du transfert: " + e.getMessage(), e);
}
}
/**
* Version SANS transaction (pour démonstration).
* NE PAS UTILISER EN PRODUCTION!
*/
public void transferNoTransaction(String fromAccount, String toAccount, BigDecimal amount) {
log.warn("⚠️ Transfert SANS transaction - DANGEREUX!");
// Débiter
accountService.debit(fromAccount, amount);
// Simuler une erreur après le débit
throw new RuntimeException("Erreur après le débit!");
// Le crédit ne sera jamais exécuté
// accountService.credit(toAccount, amount);
}
}
Partie 5: Controller et Données de Test
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;
// === COMPTES ===
@GetMapping("/accounts")
public List<Account> getAllAccounts() {
return accountService.getAllAccounts();
}
@GetMapping("/accounts/{accountNumber}")
public Account getAccount(@PathVariable String accountNumber) {
return accountService.getAccount(accountNumber);
}
// === TRANSFERTS ===
@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("Transfert réussi!");
}
@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("Transfert réussi!");
}
// === 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 Données Initiales
-- 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 (ajouter)
spring.jpa.defer-datasource-initialization=true
spring.sql.init.mode=always
Partie 6: Tests Pratiques
6.1 Test 1: Transfert Réussi
# Vérifier les soldes initiaux
curl http://localhost:8080/api/bank/accounts
# Transfert de 200€ de ACC001 vers ACC002
curl -X POST http://localhost:8080/api/bank/transfer \
-H "Content-Type: application/json" \
-d '{"from":"ACC001", "to":"ACC002", "amount":200}'
# Vérifier les nouveaux soldes
curl http://localhost:8080/api/bank/accounts
# Vérifier les logs
curl http://localhost:8080/api/bank/logs
Résultat attendu:
- ACC001: 1000 → 800€
- ACC002: 500 → 700€
- Log avec status "SUCCESS"
6.2 Test 2: Solde Insuffisant (Rollback)
# Tenter un transfert de 2000€ (ACC001 n'a que 800€)
curl -X POST http://localhost:8080/api/bank/transfer \
-H "Content-Type: application/json" \
-d '{"from":"ACC001", "to":"ACC002", "amount":2000}'
# Vérifier que les soldes n'ont PAS changé
curl http://localhost:8080/api/bank/accounts
# Vérifier que le log d'échec est présent!
curl http://localhost:8080/api/bank/logs
Résultat attendu:
- ACC001: reste 800€ (pas de changement)
- ACC002: reste 700€ (pas de changement)
- Log avec status "FAILED" et message d'erreur
6.3 Test 3: Sans Transaction (DANGEREUX)
# Redémarrer l'application pour réinitialiser les données
# Essayer le transfert sans transaction
curl -X POST http://localhost:8080/api/bank/transfer-no-tx \
-H "Content-Type: application/json" \
-d '{"from":"ACC001", "to":"ACC002", "amount":200}'
# Vérifier les soldes
curl http://localhost:8080/api/bank/accounts
Résultat attendu (BUG!):
- ACC001: 1000 → 800€ (débité!)
- ACC002: reste 500€ (jamais crédité!)
- 200€ ont disparu! 💀
Partie 7: Comprendre REQUIRES_NEW
7.1 Pourquoi le Log d'Audit est Conservé?
Regardez ce schéma:
7.2 Exercice: Modifier le Comportement
- Dans
AuditService, changezREQUIRES_NEWenREQUIRED - Relancez le test 2 (solde insuffisant)
- Observez: le log n'est plus créé en cas d'échec!
// Essayez ceci temporairement:
@Transactional(propagation = Propagation.REQUIRED) // Au lieu de REQUIRES_NEW
public void logTransaction(...) { }
Partie 8: Le Piège de la Self-Invocation
8.1 Le Problème
Ajoutez cette méthode dans TransferService:
// Méthode avec le piège de self-invocation
public void transferWithLogging(String from, String to, BigDecimal amount) {
log.info("Appel externe...");
// ⚠️ PIÈGE: Appel direct = pas de proxy = pas de transaction!
this.transfer(from, to, amount); // @Transactional ignoré!
}
8.2 La Solution
@Service
@RequiredArgsConstructor
@Slf4j
public class TransferService {
private final AccountService accountService;
private final AuditService auditService;
// Injection de soi-même pour passer par le proxy
@Autowired
private TransferService self;
public void transferWithLogging(String from, String to, BigDecimal amount) {
log.info("Appel externe...");
// ✅ Passe par le proxy = transaction active!
self.transfer(from, to, amount);
}
@Transactional
public void transfer(String from, String to, BigDecimal amount) {
// ... code existant
}
}
Partie 9: ReadOnly Transaction
9.1 Vérifier l'Optimisation
Ajoutez du logging dans AccountService:
@Transactional(readOnly = true)
public List<Account> getAllAccounts() {
log.info("Transaction readOnly = true");
List<Account> accounts = accountRepository.findAll();
// Ceci ne sera PAS persisté car readOnly = true
accounts.forEach(a -> a.setBalance(BigDecimal.ZERO));
return accounts;
}
Test:
curl http://localhost:8080/api/bank/accounts
# Les soldes affichés sont 0...
curl http://localhost:8080/api/bank/accounts
# Mais les vrais soldes sont inchangés!
Résumé
Ce que Vous Avez Appris
| Concept | Exemple |
|---|---|
| @Transactional | Garantit atomicité |
| Rollback | Annule tout en cas d'erreur |
| REQUIRES_NEW | Transaction indépendante |
| readOnly | Optimisation pour lectures |
| Self-invocation | Piège du proxy Spring |
Règles d'Or
1. Toujours utiliser @Transactional sur les opérations d'écriture
2. Utiliser REQUIRES_NEW pour les logs d'audit
3. Éviter la self-invocation
4. Utiliser readOnly = true pour les lectures
5. Ne jamais avaler les exceptions
🎯 Prochaine Étape
➡️ TP7.3: Migration avec Flyway