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

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

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

谢谢!


当前回答

我唯一一次得到这个错误是当我试图将NULL传递到集合的setter时。为了防止这种情况,我的setter是这样的:

public void setSubmittedForms(Set<SubmittedFormEntity> submittedForms) {
    if(submittedForms == null) {
        this.submittedForms.clear();
    }
    else {
        this.submittedForms = submittedForms;
    }
}

其他回答

另一个原因可能是使用龙目岛。

@Builder -导致保存Collections.emptyList(),即使你说.myCollection(new ArrayList());

@Singular -忽略类级别的默认值,并保留字段为空,即使类字段声明为myCollection = new ArrayList()

我的2美分,刚刚花了2个小时在同样的东西上:)

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

从[Intellij Idea] 2020.3版本批量运行测试时,spring-boot 2.4.1出现此问题。从IntelliJ一次只运行一个测试或从命令行运行测试时,不会出现此问题。

也许是Intellij缓存问题?

跟进:

The problem appears when running tests using the maven-surefire-plugin reuseForks true. Using reuseForks false would provide a quick fix, but the tests running time will increase dramatically. Because we are reusing forks, the database context might become dirty due to other tests that are run - without cleaning the database context afterwards. The obvious solution would be to clean the database context before running a test, but the best one should be to clean up the database context after each test (solving the root cause of the original problem). Using the @Transactional annotation on your test methods will guarantee that your database changes are rolled back at the end of the test methods. See the Spring documentation on transactions: https://docs.spring.io/spring-framework/docs/current/reference/html/testing.html#testcontext-tx.

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

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

我有同样的问题,但它是当集合为空。只有在Set集合中,在List中工作正常。您可以尝试使用hibernate注释@LazyCollection(LazyCollectionOption.FALSE)而不是JPA注释fetch = FetchType.EAGER。

我的解决方案: 这是我的配置和工作良好

@OneToMany(mappedBy = "format", cascade = CascadeType.ALL, orphanRemoval = true)
@LazyCollection(LazyCollectionOption.FALSE)
private Set<Barcode> barcodes;

@OneToMany(mappedBy = "format", cascade = CascadeType.ALL, orphanRemoval = true)
@LazyCollection(LazyCollectionOption.FALSE)
private List<FormatAdditional> additionals;