package com.ankurm.onetomany; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; import java.util.HashSet; import java.util.Set; /** The recommended shape: bidirectional, child owns the foreign key, a Set, helper methods on the parent. */ @Entity @Table(name = "departments") public class Department { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String name; // mappedBy = "department" names the field on Employee that owns the foreign key column. @OneToMany(mappedBy = "department", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) private Set employees = new HashSet<>(); protected Department() { } public Department(String name) { this.name = name; } // The invariant that keeps both sides of the association in step. public void addEmployee(Employee employee) { employees.add(employee); employee.setDepartment(this); } public void removeEmployee(Employee employee) { employees.remove(employee); employee.setDepartment(null); } public Long getId() { return id; } public String getName() { return name; } public Set getEmployees() { return employees; } }