删除时 在休眠状态中设置 null @OneToMany

2022-09-01 17:33:19

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

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

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

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

我想实现下一个:当我删除一个部门时,这个部门的所有级的ik_parent_department_id参数都设置为null。任何想法如何做到这一点?


答案 1

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

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

为了避免可能的重复“设置空代码”和完整性违规异常在父级删除中实现Entity

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

答案 2

您必须将子项显式设置为 null。ik_parent_department_id

Department parentDepartment = (Department) session.load(Department.class, id);
session.delete(parentDepartment);
for (Department child : parentDepartment.getChildren()){
    child.setParentDepartment(null);
} 
session.flush();

使用级联,您只能设法删除子级。Departments


推荐