Reputation: 437
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?
Upvotes: 1
Views: 1831
Reputation: 1590
Before deleting group, iterate over groups job opening list and set null to group field. Or write an update query which nulls job openings table's group field. Something like,
Group group = entityManager.find(Group.class, groupId);
for (JobOpening aJob : group.getJobs()) {
aJob.setGroup(null);
entityManager.merge(aJob);
entityManager.flush();
}
//Then delete group
entityManager.remove(group);
With query, something like,
entityManager.createQuery("update JobOpening set group = null where group.id = :groupId")
.setParameter(groupId)
.executeUpdate();
Then remove group.
Upvotes: 3