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

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

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

谢谢!


当前回答

检查所有你给sonEntities赋值的地方。您所引用的链接明确指出了创建一个新的HashSet,但您在重新分配该集合时可能会遇到此错误。例如:

public void setChildren(Set<SonEntity> aSet)
{
    this.sonEntities = aSet; //This will override the set that Hibernate is tracking.
}

通常在构造函数中只需要“新建”一次集合。每当您想要向列表中添加或删除一些内容时,您都必须修改列表的内容,而不是分配一个新的列表。

添加子代:

public void addChild(SonEntity aSon)
{
    this.sonEntities.add(aSon);
}

移除儿童:

public void removeChild(SonEntity aSon)
{
    this.sonEntities.remove(aSon);
}

其他回答

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

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

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

"children": [],

向请求体解决了问题。

我也犯了同样的错误。我的问题是,保存实体后映射的集合仍然为空,当试图更新实体时抛出异常。对我有帮助的是:保存实体,然后进行刷新(集合不再为空),然后执行更新。也许用new ArrayList()来初始化集合也会有帮助。

检查所有你给sonEntities赋值的地方。您所引用的链接明确指出了创建一个新的HashSet,但您在重新分配该集合时可能会遇到此错误。例如:

public void setChildren(Set<SonEntity> aSet)
{
    this.sonEntities = aSet; //This will override the set that Hibernate is tracking.
}

通常在构造函数中只需要“新建”一次集合。每当您想要向列表中添加或删除一些内容时,您都必须修改列表的内容,而不是分配一个新的列表。

添加子代:

public void addChild(SonEntity aSon)
{
    this.sonEntities.add(aSon);
}

移除儿童:

public void removeChild(SonEntity aSon)
{
    this.sonEntities.remove(aSon);
}

小心

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

这种方法太过打破休眠。