java - 使用 JPA Hibernate 自动保存子对象

标签 java database hibernate

我在父表和子表之间有一对多的关系。在父对象中我有一个

List<Child> setChildren(List<Child> childs)

我在 Child 表中也有一个外键。此外键是引用数据库中父行的 ID。所以在我的数据库配置中,这个外键不能为 NULL。 此外键也是 Parent 表中的主键。

所以我的问题是如何通过执行以下操作自动保存子对象:

session.save(parent);

我尝试了上述方法,但我收到一个数据库错误,提示 Child 表中的外键字段不能为 NULL。有没有办法告诉 JPA 自动将此外键设置为子对象,以便它可以自动保存子对象?

提前致谢。

最佳答案

I tried the above but I'm getting a database error complaining that the foreign key field in the Child table can not be NULL. Is there a way to tell JPA to automatically set this foreign key into the Child object so it can automatically save children objects?

嗯,这里有两件事。

首先,您需要级联保存操作(但我的理解是您正在这样做,否则在“子”表中插入期间您不会违反 FK 约束)

其次,您可能有双向关联,我认为您没有正确设置“链接的两侧”。你应该这样做:

Parent parent = new Parent();
...
Child c1 = new Child();
...
c1.setParent(parent);

List<Child> children = new ArrayList<Child>();
children.add(c1);
parent.setChildren(children);

session.save(parent);

一种常见的模式是使用链接管理方法:

@Entity
public class Parent {
    @Id private Long id;

    @OneToMany(mappedBy="parent")
    private List<Child> children = new ArrayList<Child>();

    ...

    protected void setChildren(List<Child> children) {
        this.children = children;
    }

    public void addToChildren(Child child) {
        child.setParent(this);
        this.children.add(child);
    }
}

而代码变成:

Parent parent = new Parent();
...
Child c1 = new Child();
...

parent.addToChildren(c1);

session.save(parent);
引用

关于java - 使用 JPA Hibernate 自动保存子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3927091/

相关文章:

java - 是什么导致了这个空指针异常?

android - 将字符串保存到 .txt 文件中还是将它们放入数据库中?

java - 反转每个奇数字符串并将它们加在一起

java - 基于图 block 的 map 滚动

java - Spring-security/登录重定向

Hibernate,按组合键的属性查询

java - Hibernate 5.0.2 与 Sqlite — 由于错误而无法使其工作

sql - 用于通配符查找的正则表达式帮助

php - 如何创建 Web 前端以在后台访问 Postgres 数据库?

java - 使用 TABLE_PER_CLASS 继承策略在 JPA 模式上存储子实体时写入父实体的策略