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

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

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

谢谢!


当前回答

这与之前的答案相反,我有完全相同的错误:“级联=“all-delete-orphan”的集合不再引用....”,当我的setter函数看起来像这样:

public void setTaxCalculationRules(Set<TaxCalculationRule> taxCalculationRules_) {
    if( this.taxCalculationRules == null ) {
        this.taxCalculationRules = taxCalculationRules_;
    } else {
        this.taxCalculationRules.retainAll(taxCalculationRules_);
        this.taxCalculationRules.addAll(taxCalculationRules_);
    }
}

然后当我把它改成简单的版本时,它就消失了:

public void setTaxCalculationRules(Set<TaxCalculationRule> taxCalculationRules_) {
    this.taxCalculationRules = taxCalculationRules_;
}

(hibernate版本-尝试了5.4.10和4.3.11。在回到setter中的简单赋值之前,花了几天时间尝试各种解决方案。现在很困惑为什么会这样。)

其他回答

@OneToMany(mappedBy = "entity_b", cascade = [CascadeType.]所有],orphanRemoval = true)

我也遇到了同样的错误。当我删除上面结构中的;"orphanRemoval = true"部分时,它工作了

当我设置parent时,拥有的实体实例不再引用级联= " all-delete-orphan "的集合。setChildren(新ArrayList < >())。当我改为parent.getChildren().clear()时,它解决了这个问题。

请查看更多详细信息:HibernateException - cascade="all-delete-orphan"的集合不再被所属实体实例引用。

我使用@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);
            }
        }
    }
}

我在尝试使用TreeSet时遇到了这个问题。我用TreeSet初始化了oneToMany

@OneToMany(mappedBy = "question", fetch = FetchType.EAGER, cascade = { CascadeType.ALL }, orphanRemoval=true)
@OrderBy("id")
private Set<WizardAnswer> answers = new TreeSet<WizardAnswer>();

但是,这将带来上述问题中所描述的错误。看起来hibernate支持SortedSet如果你把上面的行改成

@OneToMany(mappedBy = "question", fetch = FetchType.EAGER, cascade = { CascadeType.ALL }, orphanRemoval=true)
@OrderBy("id")
private SortedSet<WizardAnswer> answers;

它像魔法一样起作用:) 更多关于hibernate SortedSet的信息可以在这里

我在用JSON post请求更新实体时遇到了这种情况。 当我在没有关于子节点数据的情况下更新实体时发生错误,即使没有子节点数据。 添加

"children": [],

向请求体解决了问题。