java - Hibernate 使用 OneToMany 添加模型

标签 java spring hibernate

我有一个有地址的 PersonModel。
看起来像这样:

public class PersonModel {
    @ManyToOne(fetch = FetchType.LAZY)
    private AddressModel address;
}

public class AddressModel {
    private String street;
    private String city;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "address", cascade = CascadeType.ALL)
    private Set<PersonModel> persons;
}

现在,当我从我的客户那里得到这个 JSON 时:

{
    "person": {
        "address": {
            "street": "Examplestreet",
            "city": "Examplevillage"
        }
    }
}

然后尝试这样保存它:

personModelRepository.save(myJSON.person);

Hibernate 总是会抛出一个TransientPropertyValueException

object references an unsaved transient instance - save the transient instance before flushing

我真的必须先保存与人相关的每个 DB-Entry 还是有其他方法?

最佳答案

尝试在 @ManyToOne 注释中添加 CascadeType.ALL

这实现了如果您保存您的地址,您的人会自动保存

关于java - Hibernate 使用 OneToMany 添加模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40530286/

相关文章:

java - 如何点击一个按钮,使一个不可见的按钮出现在android中?

java - hibernate -级联类型持续存在多对多关系

java - 为什么我的项目中不能使用 @Before 注解? "Before cannot be resolved to a type"

java - 将 hibernate 对象作为参数添加到 jasperreports

java - 如何在spring上正确地从file.properties设置hibernate?

java - Hibernate 中的 setText() 是什么?

java - Hibernate 无法实例化抽象类或接口(interface) : java. util.List

java - 向灰度图像添加颜色

java - 使用@DataJpaTest 设置自定义方案

java - 单例的奇怪行为