在@OneToMany中,在hibernate中删除set null

Mah*_*leh 19 hibernate

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

  1. 许多部门可以在一个父部门:

    @ManyToOne
    @JoinColumn(name = "ik_parent_department_id")
    private Department parentDepartment;
    
    Run Code Online (Sandbox Code Playgroud)
  2. 一个父部门可以有很多部门:

    @OneToMany(mappedBy = "parentDepartment")
    private Set<Department> children = new HashSet<Department>(0);
    
    Run Code Online (Sandbox Code Playgroud)

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

Xav*_*ica 10

您必须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();
Run Code Online (Sandbox Code Playgroud)

通过级联,您只能设法删除子级Departments.

  • 所以hibernate中没有这样的功能或解决方法? (3认同)
  • 不,那里没有。在某些数据库中可以在数据库中设置 fk 来执行此操作,但支持有限。例如,使用 sql server,您会遇到循环引用的问题,因此将逻辑实现到代码中看起来像建议的那样。另请参阅:http://stackoverflow.com/questions/9944137/have-jpa-hibernate-to-replicate-the-on-delete-set-null-functionity (3认同)

pir*_*rho 9

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

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

而为了避免可能出现的重复着“集零码”及完整性违反了父去除异常父落实Entity

@PreRemove
private void preRemove() {
   children.forEach( child -> child.setParent(null));
}
Run Code Online (Sandbox Code Playgroud)


JB *_*zet 5

只需编码:

for (Department child : parent.getChildren()) {
    child.setParentDepartment(null);
}
session.delete(parent);
Run Code Online (Sandbox Code Playgroud)