Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b4H5ph3J7k2MJnRuVH
61 lines
1.5 KiB
Java
61 lines
1.5 KiB
Java
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<Employee> 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<Employee> getEmployees() {
|
|
return employees;
|
|
}
|
|
}
|