【问题标题】:Keeping entity relationship in sync when deleting child in JPA在 JPA 中删除子项时保持实体关系同步
【发布时间】:2019-01-15 12:30:32
【问题描述】:

我已经读到您需要使具有关系的实体保持同步,即当您从父实体中删除子实体时,您还应该在子实体中将持有父实体的属性设置为 null。在我的示例中,我有以下父实体:

public class Parent {
    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Child> children;
}

还有孩子:

public class Child {
    @ManyToOne(optional = false)
    private Parent parent;

    public void setParent(Parent parent) {
        this.parent = parent;
    }
}

从父级中删除子级的代码如下(在此示例中,Parent 可以在其列表中多次包含相同的Child):

public void removeChild(Child child) {
    List<Child> childrenToRemove = this.children.stream()
        .filter(c -> c.equals(child))
        .collect(Collectors.toList());
    childrenToRemove.forEach(child -> child.setParent(null));
    this.children.removeAll(childrenToRemove);
}

我首先将每个孩子的Parent 设置为NULL,然后将它们从集合中删除。这使实体保持同步。我还可以将removeChild 代码更改为以下内容:

public void removeChild(Child child) {
    this.children.removeIf(c -> c.equals(child));
}

当然,在这种情况下,实体不会保持同步,因为每个 Child 实体仍然具有对 Parent 的引用。为了解决这个问题,我可以将以下内容添加到 Child 实体:

@PreRemove
public void preRemove() {
    this.parent = null;
}

我现在的问题是,如果 Child 实体也保存在不同父实体的列表中,例如实体AnotherParent 还保留了Child 实体的列表,然后我是否应该将this.anotherParent = null 添加到上面定义的@PreRemove 方法中?如果Child 与其他实体有单向关系怎么办(即对方没有保留Child 实体的列表,是否应该将它们设置为null?)。

【问题讨论】:

    标签: java hibernate jpa orm entity-relationship


    【解决方案1】:

    您应该保持双向关联同步,以便实体状态转换可以传播并避免代码中难以跟踪的错误。

    我现在的问题是,如果 Child 实体也保存在一个 不同的父实体,例如实体 AnotherParent 也 保留子实体的列表,然后我应该添加 this.anotherParent = null 到上面定义的@PreRemove 方法?

    如果AnotherParent实体没有加载到当前运行的Persistence cOntext中,则不必这样做,因为内存中不存在父端集合。

    如果 Child 与其他实体有单向关系怎么办 (即对方没有保留子实体的列表,应该 它们被设置为空?)。

    如果你不这样做,你会得到一个ConstraintViolationException,因为单向关联更像是多对多而不是一对多。

    【讨论】:

    • 有道理,我想知道你怎么知道AnotherParent当前是否加载到正在运行的PC中?
    • 您必须检查数据访问逻辑。这是根据每个用例处理的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多