Inverse side (Department) :
@OneToMany(mappedBy = "department", fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
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 merging 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 Employees and hence, there is a null foreign key (Thus, ON DELETE SET NULL is specified in the back-end system).
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.