Add one-to-many module: @OneToMany in Hibernate 7.4.16.Final (unidirectional join table vs @JoinColumn vs mappedBy, Set vs List removal cost, sync helper, fetch defaults, N+1, MultipleBagFetchException fixes, id-hashCode trap)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b4H5ph3J7k2MJnRuVH
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
bdae169002
commit
eab5461d86
@@ -0,0 +1,60 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user