我读到您需要保持具有同步关系的实体,即当您从父实体中删除子实体时,您还应该将子实体中将父实体保存为 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/