Pular para o conteúdo principal

TP6.2 - Relações Employee-Department

Objetivos​

Ao final deste TP, você será capaz de:

  1. ✅ Criar entidades com relações @ManyToOne e @OneToMany
  2. ✅ Gerenciar relações bidirecionais
  3. ✅ Utilizar operações de cascade
  4. ✅ Evitar o problema N+1 com JOIN FETCH

Duração estimada: 2h


Pré-requisitos​

  • ✅ Capítulo 2 do Módulo 6 concluído
  • ✅ TP6.1 concluído
  • ✅ Maven 3.9+ e Java 17+

Preparação: Novo Projeto​

Spring Initializr​

Configuração:

  • Artifact: employee-department
  • Dependências: Spring Web, Spring Data JPA, H2 Database

Exercício 1: Criar as Entidades​

Etapa 1.1: Entidade Department​

Arquivo: 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<>();

// Construtores
public Department() {}

public Department(String name, String location) {
this.name = name;
this.location = location;
}

// Métodos auxiliares para sincronizar a relação
public void addEmployee(Employee employee) {
employees.add(employee);
employee.setDepartment(this);
}

public void removeEmployee(Employee employee) {
employees.remove(employee);
employee.setDepartment(null);
}

// Getters e 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; }
}

Etapa 1.2: Entidade Employee​

Arquivo: 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;

// Construtores
public Employee() {}

public Employee(String name, String email, Double salary) {
this.name = name;
this.email = email;
this.salary = salary;
}

// Getters e 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; }
}

Exercício 2: Criar os Repositories​

Etapa 2.1: DepartmentRepository​

Arquivo: 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étodo simples
List<Department> findByLocation(String location);

// Com JOIN FETCH para evitar N+1
@Query("SELECT d FROM Department d JOIN FETCH d.employees")
List<Department> findAllWithEmployees();
}

Etapa 2.2: EmployeeRepository​

Arquivo: 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> {

// Percorrer a relação
List<Employee> findByDepartmentName(String deptName);

// Com salário
List<Employee> findBySalaryGreaterThan(Double minSalary);

// Departamento E salário
List<Employee> findByDepartmentNameAndSalaryGreaterThan(
String deptName,
Double minSalary
);

// Com JOIN FETCH
@Query("SELECT e FROM Employee e JOIN FETCH e.department")
List<Employee> findAllWithDepartment();

// Consulta personalizada
@Query("SELECT e FROM Employee e WHERE e.department.location = :location")
List<Employee> findByDepartmentLocation(@Param("location") String location);
}

Exercício 3: Inicializar os Dados​

Arquivo: 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("=== Inicialização ===");

// 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 criados ===");
};
}
}

Exercício 4: Criar os Controllers​

Controller Departments​

Arquivo: 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​

Arquivo: 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();
}
}

Exercício 5: Testar​

Teste 1: Recuperar todos os departamentos​

GET http://localhost:8080/api/departments

⚠️ Observe o console SQL:

SELECT * FROM departments;
-- Sem JOIN! Os employees não são carregados (LAZY)

Teste 2: Recuperar um departamento com seus funcionários​

GET http://localhost:8080/api/departments/1

Console SQL:

SELECT * FROM departments WHERE id = 1;
SELECT * FROM employees WHERE department_id = 1; -- 2ª consulta!

Isso é normal com LAZY!


Teste 3: Evitar N+1 com JOIN FETCH​

GET http://localhost:8080/api/departments/with-employees

Console SQL:

-- Apenas 1 consulta com JOIN!
SELECT d.*, e.*
FROM departments d
LEFT JOIN employees e ON d.id = e.department_id;

✅ Muito mais performático!


Teste 4: Funcionários de um departamento​

GET http://localhost:8080/api/employees/department/IT

Resultado: Alice, Bob, Charlie


Teste 5: Funcionários com salário > 60000​

GET http://localhost:8080/api/employees/salary-above/60000

Resultado: Alice (75k), Charlie (80k), Eve (60k)


Challenge: CRUD Completo com Relações​

Crie estes endpoints:

  1. POST /api/departments - Criar um departamento
  2. POST /api/employees - Criar um funcionário (com department_id)
  3. PUT /api/employees/{id}/department/{deptId} - Alterar o departamento de um funcionário
  4. DELETE /api/departments/{id} - Remover um departamento (e seus funcionários em cascade)
  5. GET /api/departments/{id}/employees - Funcionários de um departamento específico

Próxima Etapa​

Avance para o TP3 para a avaliação completa!

➡️ TP6.3: Exercício Airport

⬅️ TP anterior: Convenções

⬅️ Voltar ao Módulo 6