TP6.2 - Relaciones Employee-Department
Objetivos
Al final de este TP, usted será capaz de:
- ✅ Crear entidades con relaciones @ManyToOne y @OneToMany
- ✅ Gestionar relaciones bidireccionales
- ✅ Utilizar operaciones de cascada
- ✅ Evitar el problema N+1 con JOIN FETCH
Duración estimada: 2h
Prerrequisitos
- ✅ Capítulo 2 del Módulo 6 completado
- ✅ TP6.1 completado
- ✅ Maven 3.9+ y Java 17+
Preparación: Nuevo Proyecto
Spring Initializr
Configuración:
- Artifact:
employee-department - Dependencias: Spring Web, Spring Data JPA, H2 Database
Ejercicio 1: Crear las Entidades
Paso 1.1: Entidad Department
Archivo: 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; }
}
Paso 1.2: Entidad Employee
Archivo: 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; }
}
Ejercicio 2: Crear los Repositories
Paso 2.1: DepartmentRepository
Archivo: 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();
}
Paso 2.2: EmployeeRepository
Archivo: 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);
}
Ejercicio 3: Inicializar los Datos
Archivo: 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("=== Inicialización ===");
// Departamento 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);
// Departamento 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);
// Departamento 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() + " departamentos creados ===");
};
}
}
Ejercicio 4: Crear los Controllers
Controller Departments
Archivo: 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
Archivo: 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();
}
}
Ejercicio 5: Probar
Prueba 1: Recuperar todos los departamentos
GET http://localhost:8080/api/departments
⚠️ Mire la consola SQL:
SELECT * FROM departments;
-- ¡Sin JOIN! Los employees no se cargan (LAZY)
Prueba 2: Recuperar un departamento con sus empleados
GET http://localhost:8080/api/departments/1
Consola SQL:
SELECT * FROM departments WHERE id = 1;
SELECT * FROM employees WHERE department_id = 1; -- ¡Segunda consulta!
¡Esto es normal con LAZY!
Prueba 3: Evitar N+1 con JOIN FETCH
GET http://localhost:8080/api/departments/with-employees
Consola SQL:
-- ¡Solo 1 consulta con JOIN!
SELECT d.*, e.*
FROM departments d
LEFT JOIN employees e ON d.id = e.department_id;
✅ ¡Mucho más eficiente!
Prueba 4: Empleados de un departamento
GET http://localhost:8080/api/employees/department/IT
Resultado: Alice, Bob, Charlie
Prueba 5: Empleados con salario > 60000
GET http://localhost:8080/api/employees/salary-above/60000
Resultado: Alice (75k), Charlie (80k), Eve (60k)
Challenge: CRUD Completo con Relaciones
Cree estos endpoints:
- POST /api/departments - Crear un departamento
- POST /api/employees - Crear un empleado (con department_id)
- PUT /api/employees/{id}/department/{deptId} - Cambiar el departamento de un empleado
- DELETE /api/departments/{id} - Eliminar un departamento (y sus empleados en cascada)
- GET /api/departments/{id}/employees - Empleados de un departamento específico
Próximo Paso
¡Pase al TP3 para la evaluación completa!