在 Hibernate/JPA 中保存一个 object 和孩子 - @OneToMany

save an object with childs in Hibernate/JPA - @OneToMany

在 Hibernate 中我想保存一个 object 有一个 child.In parent Object 我有一组其他 类 是 child. parent 与 child.

具有@OneToMany 关系

parent :

@Entity
public class TalentIdentitySetting {

 @OneToMany(fetch = FetchType.LAZY, mappedBy = "setting", cascade = CascadeType.ALL, orphanRemoval = true)
 private Set<TalentIdentitySettingPower> settingPowers;

 @OneToMany(fetch = FetchType.LAZY, mappedBy = "setting", cascade = CascadeType.ALL, orphanRemoval = true)
 private Set<TalentIdentitySettingSpeciality> settingSpecialities;

}

child :

@Entity
public class TalentIdentitySettingPower {

 @ManyToOne(fetch = FetchType.LAZY)
 @JoinColumn(name = "IDENTITY_SETTING_ID", nullable = false)
 private TalentIdentitySetting setting;

 @ManyToOne(fetch = FetchType.LAZY)
 @JoinColumn(name = "POWER_ID", nullable = false)
 private BasePower power;

}

如何在一笔交易中同时保存 parent 和 child。 这是我的问题;当 child 想要保存时, parent 还没有保存,并说 parent key not found。 事实上,hibernate 应该先保存 parent 然后再保存 child.

请帮助我。

我相信你的 JPA 注释是正确的,这很可能是你的 TalentIdentitySettingPower.setting 在保存之前没有被设置

假设您有以下代码

        TalentIdentitySetting setting = new TalentIdentitySetting();
        HashSet<TalentIdentitySettingPower> powers = new HashSet<>();
        powers.add(new TalentIdentitySettingPower());
        powers.add(new TalentIdentitySettingPower());
        powers.add(new TalentIdentitySettingPower());
        setting.setSettingPowers(powers);
        repository.save(setting);

这将失败并抱怨 null-value 问题

如果在TalentIdentitySettingPower中添加构造方法

    public TalentIdentitySettingPower(TalentIdentitySetting setting) {
        this.setting = setting;
    }

        TalentIdentitySetting setting = new TalentIdentitySetting();
        HashSet<TalentIdentitySettingPower> powers = new HashSet<>();
        powers.add(new TalentIdentitySettingPower(setting));
        powers.add(new TalentIdentitySettingPower(setting));
        powers.add(new TalentIdentitySettingPower(setting));
        setting.setSettingPowers(powers);
        repository.save(setting);

这将成功地将值保存到数据库中。

根据你的示例,我创建了一个应用程序https://github.com/hepoiko/stack-63703687