【问题标题】:On delete set null in hibernate in @OneToMany在 @OneToMany 的休眠中删除设置 null
【发布时间】:2012-01-04 19:35:48
【问题描述】:

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

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

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

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

我想实现下一个:当我删除一个部门,然后是所有childrenik_parent_department_id参数此部门的strong>设置为null。任何想法如何做到这一点?

【问题讨论】:

标签: java hibernate jpa one-to-many


【解决方案1】:

您必须将孩子的 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

【讨论】:

  • 不,没有。可以在 db 中设置 fk 以在某些数据库中执行此操作,但支持有限。例如。使用 sql server,您会遇到循环引用问题,因此将逻辑实现到代码中看起来就像建议的那样。另见:stackoverflow.com/questions/9944137/…
【解决方案2】:

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

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

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

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

【讨论】:

  • 谢谢。这行得通。我的问题是:有没有办法只通过级联操作来做到这一点?
【解决方案3】:

只需编码:

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

【讨论】:

    猜你喜欢
    • 2022-12-03
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多