在Hibernate中@OneToMany中的删除设置为空

28

我有一个Department实体,其关系如下:

  1. 许多部门可以位于一个父部门中:

    @ManyToOne
    @JoinColumn(name = "ik_parent_department_id")
    private Department parentDepartment;
    
  2. 一个父部门可以有多个子部门

  3. @OneToMany(mappedBy = "parentDepartment")
    private Set<Department> children = new HashSet<Department>(0);
    

我想实现以下功能: 当我删除一个部门时,将此部门的所有子部门ik_parent_department_id参数设置为null。你有什么想法吗?


3个回答

14

使用JPA,您可能在父Entity中拥有类似以下的东西

@OneToMany(mappedBy="parent", cascade={CascadeType.PERSIST})
Collection<Child> children;

为避免在删除父对象时出现可能重复的“设置为空代码”和完整性违规异常,请在父类Entity中实现。

@PreRemove
private void preRemove() {
   children.forEach( child -> child.setParent(null));
}

谢谢。这个可行。我的问题是:有没有一种只使用级联操作来完成这个的方法? - jksevend

13

你需要显式地将子节点的ik_parent_department_id设置为null。

Department parentDepartment = (Department) session.load(Department.class, id);
session.delete(parentDepartment);
for (Department child : parentDepartment.getChildren()){
    child.setParentDepartment(null);
} 
session.flush();
使用级联删除,您只能成功删除子部门 Departments

3
不,没有这样的功能。在某些数据库中可以设置外键来实现此功能,但支持有限。例如,在使用SQL Server时,会遇到循环引用的问题,因此将逻辑实现到代码中似乎是更好的选择。请参见:https://dev59.com/i2kw5IYBdhLWcg3wXpac - s.Daniel

6

只需编码:

for (Department child : parent.getChildren()) {
    child.setParentDepartment(null);
}
session.delete(parent);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接