这对我来说似乎是一个如此简单的场景,但我无法在网上或印刷中找到解决方案。我有几个像这样的物体(修剪过):
@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;
}
}
说我想删除一个Group对象。现在,JobOpening表和group_hiringManager表中存在依赖关系,导致删除功能失败。我不想级联删除,因为管理员有其他组,并且jobopenings可以是无组。我已经尝试覆盖我的GroupManager的remove()函数来删除依赖项,但似乎无论我做什么它们都存在,删除失败!
删除此对象的正确方法是什么?
答案 0 :(得分:3)
在删除组之前,迭代组作业开放列表并将null设置为组字段。或者编写一个更新查询,该查询使作业开始表的组字段为空。像,
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);
使用查询,例如,
entityManager.createQuery("update JobOpening set group = null where group.id = :groupId")
.setParameter(groupId)
.executeUpdate();
然后删除组。