Deleting objects with FK constraints in Spring/Hibernate
- by maxdj
This seems like such a simple scenario to me, yet I cannot for the life of my find a solution online or in print. I have several objects like so (trimmed down):
@Entity
public class Group extends BaseObject implements Identifiable<Long> {
private Long id;
private String name;
private Set<HiringManager> managers = new HashSet<HiringManager>();
private List<JobOpening> jobs;
@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(
name="group_hiringManager",
joinColumns=@JoinColumn(name="group_id"),
inverseJoinColumns=@JoinColumn(name="hiringManager_id")
)
public Set<HiringManager> getManagers() {
return managers;
}
@OneToMany(mappedBy="group", fetch=FetchType.EAGER)
public List<JobOpening> getJobs() {
return jobs;
}
}
@Entity
public class JobOpening extends BaseObject implements Identifiable<Long> {
private Long id;
private String name;
private Group group;
@ManyToOne
@JoinColumn(name="group_id", updatable=false, nullable=true)
public Group getGroup() {
return group;
}
}
@Entity
public class HiringManager extends User {
@ManyToMany(mappedBy="managers", fetch=FetchType.EAGER)
public Set<Group> getGroups() {
return groups;
}
}
Say I want to delete a Group object. Now there are dependencies on it in the JobOpening table and in the group_hiringManager table, which cause the delete function to fail. I don't want to cascade the delete, because the managers have other groups, and the jobopenings can be groupless. I have tried overriding the remove() function of my GroupManager to remove the dependencies, but it seems like no matter what I do they persist, and the delete fails!
What is the right way to remove this object?