我有以下问题时,试图更新我的实体:

"A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance".

我有一个父实体,它有一个Set<…>的子实体。当我尝试更新它时,我得到了要设置到这个集合的所有引用并设置它。

下面的代码表示我的映射:

@OneToMany(mappedBy = "parentEntity", fetch = FetchType.EAGER)
@Cascade({ CascadeType.ALL, CascadeType.DELETE_ORPHAN })
public Set<ChildEntity> getChildren() {
    return this.children;
}

我已经尝试清理Set<..只有>,根据这个:如何“可能”解决问题,但它没有工作。

如果你有什么想法,请告诉我。

谢谢!


当前回答

我最近在重构一些代码时遇到了这个问题。原始的(正确的)代码是这样的:

public virtual IEnumerable<SubscriptionPurchase> Purchases => _purchases;
public virtual SubscriptionPurchase MostRecentPurchase => _purchases.OrderByDescending(p => p.PurchaseDateUtc).FirstOrDefault();

我尝试通过将. orderbydescent移动到. purchasing属性来更改代码。这个更改破坏了代码,并导致OP中的引用错误:

public virtual IEnumerable<SubscriptionPurchase> Purchases => _purchases.OrderByDescending(p => p.PurchaseDateUtc);
public virtual SubscriptionPurchase MostRecentPurchase => Purchases.FirstOrDefault();

直到试图保存包含. purchasing属性的父对象时,错误才显示出来。

正如对这个问题的其他回答所指出的那样,出现这个问题是因为集合正在重置(在我的例子中是在对. purchasing的每个访问上)。

其他回答

我通过这样做来固定:

1. 清除现有的子列表,以便从数据库中删除它们

parent.getChildren().clear();

2. 将上面创建的新子列表添加到现有列表中

parent.getChildren().addAll(children);

希望这篇文章能帮助你解决这个错误

而不是分配新的集合

public void setChildren(Set<ChildEntity> children) {
    this.children = children;
}

将所有元素替换为

public void setChildren(Set<ChildEntity> children) {
    Collections.replaceAll(this.children,children);
}

下面的解决方案对我很有效

//Parent class
@OneToMany(mappedBy = 'parent', 
           cascade= CascadeType.ALL, orphanRemoval = true)
@OrderBy(value="ordinal ASC")
List<Child> children = new ArrayList<>()

//Updated setter of children 
public void setChildren(List<Children> children) {
    this.children.addAll(children);
    for (Children child: children)
        child.setParent(this);
}


//Child class
@ManyToOne
@JoinColumn(name="Parent_ID")
private Parent parent;

当我在我的父实体中使用这些注释时,我面临着类似的问题:

@Cascade({ CascadeType.ALL, CascadeType.DELETE_ORPHAN })

错误地,我试图在数据库中保存一个空父对象,并正确设置我的实体对象的值解决了我的错误。所以,做检查,如果你是愚蠢的设置错误的值或试图在数据库中保存一个空对象。

当我们以孩子为最终选择时,问题就解决了。

我们不应该在构造函数和setter中改变子对象的引用。