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

"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<..只有>,根据这个:如何“可能”解决问题,但它没有工作。

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

谢谢!


当前回答

@OneToMany(mappedBy = 'parent', cascade= CascadeType.ALL, orphanRemoval = true)
List<Child> children = new ArrayList<>();

当我将子对象添加到现有的子对象列表中时,我遇到了相同的错误。

childService.saveOrUpdate(child);
parent.addToChildren(child);
parentService.saveOrUpdate(parent);

解决我问题的是:

child = childService.saveOrUpdate(child);

现在孩子复活了其他细节以及它工作得很好。

其他回答

我使用@user2709454方法,但改进很小。

public class User {
    private Set<Role> roles;

    public void setRoles(Set<Role> roles) {
        if (this.roles == null) {
            this.roles = roles;
        } else if(this.roles != roles) { // not the same instance, in other case we can get ConcurrentModificationException from hibernate AbstractPersistentCollection
            this.roles.clear();
            if(roles != null){
                this.roles.addAll(roles);
            }
        }
    }
}

小心

BeanUtils.copyProperties(newInsum, insumOld,"code");

这种方法太过打破休眠。

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

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

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

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

//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;

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

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的每个访问上)。