TP6.2 - Relations Employee-Department
Objectifs
À la fin de ce TP, vous serez capable de:
- ✅ Créer des entités avec relations @ManyToOne et @OneToMany
- ✅ Gérer les relations bidirectionnelles
- ✅ Utiliser les cascade operations
- ✅ Éviter le problème N+1 avec JOIN FETCH
Durée estimée: 2h
Prérequis
- ✅ Chapitre 2 du Module 6 complété
- ✅ TP6.1 complété
- ✅ Maven 3.9+ et Java 17+
Préparation: Nouveau Projet
Spring Initializr
Configuration:
- Artifact:
employee-department - Dependencies: Spring Web, Spring Data JPA, H2 Database
Exercice 1: Créer les Entités
Étape 1.1: Entité Department
Fichier: model/Department.java
package com.example.relations.model;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "departments")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String location;
// ONE department has MANY employees
@OneToMany(mappedBy = "department", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Employee> employees = new ArrayList<>();
// Constructeurs
public Department() {}
public Department(String name, String location) {
this.name = name;
this.location = location;
}
// Helper methods pour synchroniser la relation
public void addEmployee(Employee employee) {
employees.add(employee);
employee.setDepartment(this);
}
public void removeEmployee(Employee employee) {
employees.remove(employee);
employee.setDepartment(null);
}
// Getters et Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getLocation() { return location; }
public void setLocation(String location) { this.location = location; }
public List<Employee> getEmployees() { return employees; }
public void setEmployees(List<Employee> employees) { this.employees = employees; }
}
Étape 1.2: Entité Employee
Fichier: model/Employee.java
package com.example.relations.model;
import jakarta.persistence.*;
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private Double salary;
// MANY employees belong to ONE department
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "department_id")
private Department department;
// Constructeurs
public Employee() {}
public Employee(String name, String email, Double salary) {
this.name = name;
this.email = email;
this.salary = salary;
}
// Getters et Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public Double getSalary() { return salary; }
public void setSalary(Double salary) { this.salary = salary; }
public Department getDepartment() { return department; }
public void setDepartment(Department department) { this.department = department; }
}
Exercice 2: Créer les Repositories
Étape 2.1: DepartmentRepository
Fichier: repository/DepartmentRepository.java
package com.example.relations.repository;
import com.example.relations.model.Department;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface DepartmentRepository extends JpaRepository<Department, Long> {
// Méthode simple
List<Department> findByLocation(String location);
// Avec JOIN FETCH pour éviter N+1
@Query("SELECT d FROM Department d JOIN FETCH d.employees")
List<Department> findAllWithEmployees();
}
Étape 2.2: EmployeeRepository
Fichier: repository/EmployeeRepository.java
package com.example.relations.repository;
import com.example.relations.model.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
// Traverser la relation
List<Employee> findByDepartmentName(String deptName);
// Avec salaire
List<Employee> findBySalaryGreaterThan(Double minSalary);
// Département ET salaire
List<Employee> findByDepartmentNameAndSalaryGreaterThan(
String deptName,
Double minSalary
);
// Avec JOIN FETCH
@Query("SELECT e FROM Employee e JOIN FETCH e.department")
List<Employee> findAllWithDepartment();
// Requête personnalisée
@Query("SELECT e FROM Employee e WHERE e.department.location = :location")
List<Employee> findByDepartmentLocation(@Param("location") String location);
}
Exercice 3: Initialiser les Données
Fichier: config/DataLoader.java
package com.example.relations.config;
import com.example.relations.model.Department;
import com.example.relations.model.Employee;
import com.example.relations.repository.DepartmentRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DataLoader {
@Bean
CommandLineRunner initDatabase(DepartmentRepository deptRepo) {
return args -> {
System.out.println("=== Initialisation ===");
// Département IT
Department it = new Department("IT", "Montreal");
it.addEmployee(new Employee("Alice", "alice@example.com", 75000.0));
it.addEmployee(new Employee("Bob", "bob@example.com", 65000.0));
it.addEmployee(new Employee("Charlie", "charlie@example.com", 80000.0));
deptRepo.save(it);
// Département HR
Department hr = new Department("HR", "Quebec");
hr.addEmployee(new Employee("David", "david@example.com", 55000.0));
hr.addEmployee(new Employee("Eve", "eve@example.com", 60000.0));
deptRepo.save(hr);
// Département Sales
Department sales = new Department("Sales", "Montreal");
sales.addEmployee(new Employee("Frank", "frank@example.com", 50000.0));
sales.addEmployee(new Employee("Grace", "grace@example.com", 52000.0));
deptRepo.save(sales);
System.out.println("=== " + deptRepo.count() + " départements créés ===");
};
}
}
Exercice 4: Créer les Controllers
Controller Departments
Fichier: controller/DepartmentController.java
package com.example.relations.controller;
import com.example.relations.model.Department;
import com.example.relations.repository.DepartmentRepository;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/departments")
public class DepartmentController {
private final DepartmentRepository deptRepo;
public DepartmentController(DepartmentRepository deptRepo) {
this.deptRepo = deptRepo;
}
@GetMapping
public List<Department> getAll() {
return deptRepo.findAll();
}
@GetMapping("/{id}")
public Department getById(@PathVariable Long id) {
return deptRepo.findById(id).orElseThrow();
}
@GetMapping("/with-employees")
public List<Department> getAllWithEmployees() {
return deptRepo.findAllWithEmployees();
}
@GetMapping("/location/{location}")
public List<Department> byLocation(@PathVariable String location) {
return deptRepo.findByLocation(location);
}
}
Controller Employees
Fichier: controller/EmployeeController.java
package com.example.relations.controller;
import com.example.relations.model.Employee;
import com.example.relations.repository.EmployeeRepository;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
private final EmployeeRepository empRepo;
public EmployeeController(EmployeeRepository empRepo) {
this.empRepo = empRepo;
}
@GetMapping
public List<Employee> getAll() {
return empRepo.findAll();
}
@GetMapping("/department/{deptName}")
public List<Employee> byDepartment(@PathVariable String deptName) {
return empRepo.findByDepartmentName(deptName);
}
@GetMapping("/salary-above/{minSalary}")
public List<Employee> highSalary(@PathVariable Double minSalary) {
return empRepo.findBySalaryGreaterThan(minSalary);
}
@GetMapping("/with-department")
public List<Employee> withDepartment() {
return empRepo.findAllWithDepartment();
}
}
Exercice 5: Tester
Test 1: Récupérer tous les départements
GET http://localhost:8080/api/departments
⚠️ Regardez la console SQL:
SELECT * FROM departments;
-- Pas de JOIN! Les employees ne sont pas chargés (LAZY)
Test 2: Récupérer un département avec ses employés
GET http://localhost:8080/api/departments/1
Console SQL:
SELECT * FROM departments WHERE id = 1;
SELECT * FROM employees WHERE department_id = 1; -- 2ème requête!
C'est normal avec LAZY!
Test 3: Éviter N+1 avec JOIN FETCH
GET http://localhost:8080/api/departments/with-employees
Console SQL:
-- 1 SEULE requête avec JOIN!
SELECT d.*, e.*
FROM departments d
LEFT JOIN employees e ON d.id = e.department_id;
✅ Beaucoup plus performant!
Test 4: Employés d'un département
GET http://localhost:8080/api/employees/department/IT
Résultat: Alice, Bob, Charlie
Test 5: Employés avec salaire > 60000
GET http://localhost:8080/api/employees/salary-above/60000
Résultat: Alice (75k), Charlie (80k), Eve (60k)
Challenge: CRUD Complet avec Relations
Créez ces endpoints:
- POST /api/departments - Créer un département
- POST /api/employees - Créer un employé (avec department_id)
- PUT /api/employees/{id}/department/{deptId} - Changer le département d'un employé
- DELETE /api/departments/{id} - Supprimer un département (et ses employés en cascade)
- GET /api/departments/{id}/employees - Employés d'un département spécifique
Prochaine Étape
Passez au TP3 pour l'évaluation complète!