Inverse side (Department) :
@OneToMany(mappedBy = "department", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<Employee> employeeList = new ArrayList<Employee>(0);
Owning side (Employee) :
@JoinColumn(name = "department_id", referencedColumnName = "department_id")
@ManyToOne(fetch = FetchType.LAZY)
private Department department;
The method that merges an Employee
entity supplied by a client having a null Department
in it :
public Employee update(Employee employee) {
Department department = employee.getDepartment();
if (department == null) {
Employee managedEmployee = entityManager.find(Employee.class, employee.getEmployeeId());
// Obtain the original Employee entity which may still have its Department intact.
if (managedEmployee == null) {
throw new EntityNotFoundException();
}
Department managedDepartment = managedEmployee.getDepartment();
if (managedDepartment != null) {
managedEmployee.getDepartment().getEmployeeList().remove(managedEmployee);
// Removing an Employee entity from the list on the inverse side,
// since it will no longer be pointing to Employee after Employee is merged.
}
return entityManager.merge(employee);
}
}
The supplied Employee
is a detached entity. Suppose that Department
is optional for Employee
s and hence, there is a null foreign key (ON DELETE SET NULL
).
Is it necessary to explicitly remove an Employee
entity as shown in the update()
method above from the employee list on the inverse side of the relationship (Department
), when the supplied Employee
does not contain a Department
(because it has already been set to null by the client while editing the Employee
entity) before merging the supplied Employee
entity?
I think, the provider will keep, the Employee
reference in the list of employees on the inverse side of the relationship, on dangling otherwise.
It is generally impractical to have an employee without a department but this is just an example. Needless to mention that null foreign keys exist in other types of associations.