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

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

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

谢谢!


当前回答

我使用Spring Boot,有这个问题与一个集合,尽管没有直接覆盖它,因为我声明了一个额外的字段为同一个集合与自定义序列化和反序列化,以提供一个更前端友好的数据表示:

  public List<Attribute> getAttributes() {
    return attributes;
  }

  public void setAttributes(List<Attribute> attributes) {
    this.attributes = attributes;
  }

  @JsonSerialize(using = AttributeSerializer.class)
  public List<Attribute> getAttributesList() {
    return attributes;
  }

  @JsonDeserialize(using = AttributeDeserializer.class)
  public void setAttributesList(List<Attribute> attributes) {
    this.attributes = attributes;
  }

似乎即使我自己没有覆盖集合,反序列化也会在底层执行,从而触发这个问题。解决方案是改变与反序列化器相关联的setter,这样它就会清除列表并添加所有内容,而不是覆盖它:

  @JsonDeserialize(using = AttributeDeserializer.class)
  public void setAttributesList(List<Attribute> attributes) {
    this.attributes.clear();
    this.attributes.addAll(attributes);
  }

其他回答

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

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

可能是hibernate-enhance-maven-plugin导致的。当我启用enableLazyInitialization属性时,这个异常开始发生在我的惰性收集上。我使用的是hibernate 5.2.17.Final。

请注意以下两个hibernate问题:

https://hibernate.atlassian.net/browse/HHH-10708 https://hibernate.atlassian.net/browse/HHH-11459

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

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

实际上,我的问题是关于实体的equals和hashcode。遗留代码会带来很多问题,永远不要忘记检查它。我所做的只是保持删除孤立策略和正确的等号和hashcode。

加上我愚蠢的回答。我们正在使用Spring Data Rest。这是我们很正常的关系。这种模式在其他地方也被使用。

//Parent class
@OneToMany(mappedBy = 'parent', 
           cascade= CascadeType.ALL, orphanRemoval = true)
@LazyCollection(LazyCollectionOption.FALSE)
List<Child> children = new LinkedList<>()


//Child class
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = 'ParentID', updatable = false)
@JsonBackReference
Parent parent

对于我们创建的关系,总是打算通过它们自己的repo添加子节点。我还没有添加回购。我们的集成测试通过REST调用经历了实体的完整生命周期,因此事务将在请求之间关闭。没有子对象的repo意味着json将子对象作为主结构的一部分,而不是在_embedded中。对父进程的更新将导致问题。