Deleting objects with FK constraints in Spring/Hibernate
Posted
by
maxdj
on Stack Overflow
See other posts from Stack Overflow
or by maxdj
Published on 2010-12-28T01:21:53Z
Indexed on
2010/12/28
7:54 UTC
Read the original article
Hit count: 324
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?
© Stack Overflow or respective owner