java - 在 JPA 中删除子项时保持实体关系同步

标签 java hibernate jpa orm entity-relationship

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

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

还有 child :

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实体的列表,是否应该将它们设置为空?)。

最佳答案

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

My question now is, what if Child entity is also kept in a list of a different parent entity, e.g. the entity AnotherParent which also keeps a list of Child entities, should I then also add this.anotherParent = null to the @PreRemove method defined above?

如果当前运行的 Persistence cOntext 中未加载 AnotherParent 实体,则不必执行此操作,因为内存中不存在父端集合。

What if Child has unidirectional relationship with other entities (i.e. the other side doesn't keep a list of the Child entities, should they be set to null?).

如果您不这样做,您将收到 ConstraintViolationException,因为单向关联更像是多对多而不是一对多。

关于java - 在 JPA 中删除子项时保持实体关系同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51743338/

相关文章:

java - 在几秒钟内从 Spring MVC 中的表中获取 400K 数据

java - hibernate 代码中的 session.connection() 类型未定义

jpa - Play 1.2.3 框架 - 提交事务的正确方法

java - 具有附加字段的 JPA ManyToMany 映射

java - 如何在 Java 中缓存具有可变参数 (Varargs) 的函数的结果

java - 从 Java 对 neo4j 数据库执行查询,解析结果

java - 为什么 Java 的 TreeSet<E> remove(Object) 不带 E

java - 从 MySQL 数据库获取时抛出 TransactionSystemException | java.lang.OutOfMemory错误: Java heap space

java - Hibernate的这种分页机制有什么问题呢?

hibernate - 使用 hibernate @NamedNativeQuery 返回数值