使用 JPA Hibernate 自动保存子对象

2023-11-26

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

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

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

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

session.save(parent);

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


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

嗯,这里有两件事。

首先,您需要级联保存操作(但我的理解是,您正在这样做,否则在“子”表中插入期间不会发生 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);
References
  • Hibernate Core Reference Guide
    • 1.2.6。工作双向链接
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 JPA Hibernate 自动保存子对象 的相关文章

随机推荐