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

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

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

谢谢!


当前回答

可能是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

其他回答

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

//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会话。 我有Spring Boot Batch和RepositoryItemReader实现,其中我通过大小为10的页面请求获取实体。

例如,我的实体是:

@Entity
class JobEntity {
    @ManyToOne(fetch = FetchType.LAZY)
    private GroupEntity group;
}

@Entity
class GroupEntity {
    @OneToMany(mappedBy = "group", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
    private Set<Config> configs; 
}

批处理:在一个事务中读取器->处理器->写入器。

在该实体配置中,GroupEntity可以转义到其他线程:

进入read部分的第一个线程获取大小为10的JobEntity页面(RepositoryItemReader#doRead),该项目包含一个共享的GroupEntity对象(因为它们都指向相同的组id)。然后取第一个实体。接下来读取部分的线程一个接一个地从该页中取出JobEntity,直到耗尽该页。

所以现在线程可以访问与JobEntity实例相同的GroupEntity实例,这是不安全的多线程访问一个Hibernate会话。

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

有一个类似的bug: https://hibernate.atlassian.net/browse/HHH-9940。

以及复制它的代码:https://github.com/abenneke/sandbox/tree/master/hibernate-null-collection/src/test

有2个可能的解决方案:

集合初始化为空集合(而不是null) orphanRemoval设置为false

例如- was:

@OneToMany(cascade = CascadeType.REMOVE,
        mappedBy = "jobEntity", orphanRemoval = true)
private List<JobExecutionEntity> jobExecutionEntities;

变成:

@OneToMany(cascade = CascadeType.REMOVE,
        mappedBy = "jobEntity")
private List<JobExecutionEntity> jobExecutionEntities;

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