在@OneToMany的hibernate中删除set null [英] On delete set null in hibernate in @OneToMany

查看:400
本文介绍了在@OneToMany的hibernate中删除set null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


  1. 许多部门可以在一个家长部门中:

      @ManyToOne 
    @JoinColumn(name =ik_parent_department_id )
    私人部门parentDepartment;


  2. 一个父部门 / strong>:

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


我想实现下一个:When我删除部门,然后部门的所有子女 ik_parent_department_id 参数已设置为 null 。任何想法如何做到这一点?

解决方案

您必须设置孩子的 ik_parent_department_id 显式为null。

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

通过级联,您只能设法删除子部门

I have a Department entity which relations are as follows:

  1. Many departments can be in one parent department:

    @ManyToOne
    @JoinColumn(name = "ik_parent_department_id")
    private Department parentDepartment;
    

  2. One parent department can have many departments:

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

And I want to implement the next: When I delete a department, then the ik_parent_department_id parameter of all children of this department is set to null. Any ideas how to do that?

解决方案

You'll have to set the children's ik_parent_department_id to null explicitly.

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

With cascading you would only manage to delete child Departments.

这篇关于在@OneToMany的hibernate中删除set null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆