我在尝试更新我的实体时遇到以下问题:
"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<..>,根据这个:How to "possible" solve the problem,但它不能工作。
如果你有任何想法,请让我知道。
谢谢!
发布于 2011-04-12 00:33:09
实际上,我的问题是关于实体的equals和hashcode。遗留代码可能会带来很多问题,千万不要忘记检查它。我所做的只是保留删除-孤立策略和正确的equals和hashcode。
发布于 2012-01-12 21:18:51
方法:
public void setChildren(Set<SonEntity> aSet) {
this.sonEntities = aSet;
}
如果parentEntity
被分离,并且如果我们更新它,则工作。
但是,如果实体没有从每个上下文中分离出来(即,查找和更新操作在同一事务中),则以下方法有效。
public void setChildren(Set<SonEntity> aSet) {
//this.sonEntities = aSet; //This will override the set that Hibernate is tracking.
this.sonEntities.clear();
if (aSet != null) {
this.sonEntities.addAll(aSet);
}
}
发布于 2014-06-18 07:31:29
当我在很多地方读到hibernate不希望你给一个集合赋值时,我认为最安全的做法显然是将它设为如下所示:
class User {
private final Set<Role> roles = new HashSet<>();
public void setRoles(Set<Role> roles) {
this.roles.retainAll(roles);
this.roles.addAll(roles);
}
}
但是,这不起作用,您会得到可怕的“不再引用”错误,在这种情况下,这实际上是相当误导的。
结果是hibernate调用了您的setRoles方法,它希望在这里安装它的特殊集合类,而不接受您的集合类。这让我困惑了很长一段时间,尽管我读到了所有关于在set方法中不给集合赋值的警告。
所以我改成这样:
public class User {
private Set<Role> roles = null;
public void setRoles(Set<Role> roles) {
if (this.roles == null) {
this.roles = roles;
} else {
this.roles.retainAll(roles);
this.roles.addAll(roles);
}
}
}
因此,在第一次调用时,hibernate会安装它的特殊类,在随后的调用中,您可以自己使用该方法,而不会破坏一切。如果您想将您的类用作bean,那么您可能需要一个有效的setter,这至少看起来是有效的。
https://stackoverflow.com/questions/5587482
复制相似问题