I have two entities defined in JPA: Employee and Skill.
Between this entities is defined relationship @ManyToMany.
public class Employee {
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "employee_skill",
joinColumns = @JoinColumn(name = "employee_id"),
inverseJoinColumns = @JoinColumn(name = "skill_id")
)
private Set<Skill> skills = new HashSet<>();
}
public class Skill {
@ManyToMany(mappedBy = "skills", fetch = FetchType.LAZY)
private Set<Employee> skilledEmployees = new HashSet<>();
}
Now I have such problem: If I remove Skill entity using entity manager. It removes ok. But in @JoinTable in database employee_skill there remains associations with this removed entity (its id).
I do not want to remove Employee when I am removing Skill so all CASCADE REMOVING or orphanRemoval are not useful here.
I consider why this relationship isn't automagically removed from database. When this association in join table remains it gives me javax.persistence.EntityNotFoundException: Unable to find...
So I could remove this associations manually, before removing Skill entity. But is it really the best practice?
What will be the best practice to remove entities in @ManyToMany bidirectional relationships? When removing one entity like Employee or Skill shouldn't effect the other entity?