1

我使用休眠 5.0.8 和 spring data jpa 1.10.1

鉴于这些实体

class Model {
    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
    @JoinColumn(nullable = false)
    private Configuration configuration;

    //more fields and methods
}

class Configuration {
    @OneToMany(mappedBy = "configuration", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Setting> settings = new ArrayList<>();

    //more fields and methods
    //settings is never assigned again - I use settings.add(...) and settings.clear()
}

class Setting {
    @ManyToOne
    @JoinColumn(nullable = false)
    private Configuration configuration;

    //more fields and methods
}

模型为主,但多个模型可以使用相同的配置。模型中的级联配置是必需的,因为如果我更改配置中的任何内容,我希望它适用于使用此配置的所有模型

现在,当我使用具有设置的配置检索现有模型并保存此模型时,不对设置应用任何更改,我得到以下异常

@Transactional
public void doSomething() {
    Model model = modelRepository.findOne(0);
    //change something in the model, but no changes are made in its configuration
    //or do nothing
    modelRepository.save(model);
}

我得到以下异常

A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: Configuration.settings

我怀疑这与延迟加载和休眠尝试将空列表合并到配置中的设置有关。

我究竟做错了什么?

4

2 回答 2

0

在取消引用时检查您尝试作为孤儿清理的对象的 getter 和 setter:

尝试使用:

    public void setChildren(Set<Child> aSet) {
        //this.child= aSet; //Results in this issue
        //change to  

        this.child.clear();
        if (aSet != null) {
            this.child.addAll(aSet);
        } }
于 2018-03-08T10:07:06.310 回答
0

该问题是由使用 hibernate-enhance-maven-plugin 中的 enableLazyInitialization 引起的。我仍然不知道它为什么会导致这个错误,但是删除这个插件解决了这个问题。

我使用了这个插件,因为我想延迟加载模型中的一个大字符串字段,我将缓存在应用程序中。我现在将其更改为延迟获取的 OneToOne 关系。

于 2018-03-09T14:04:54.623 回答