使用 JPA Hibernate 自动保存子对象 [英] Save child objects automatically using JPA Hibernate

查看:35
本文介绍了使用 JPA Hibernate 自动保存子对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在父表和子表之间存在一对多关系.在父对象中,我有一个

I have a one-to-many relation between Parent and Child table. In the parent object I have a

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

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

I also have a foreign key in the Child table. This foreign key is an ID that references a Parent row in database. So in my database configuration this foreign key can not be NULL. Also this foreign key is the primary key in the Parent table.

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

So my question is how I can automatically save the children objects by doing something like this:

session.save(parent);

我尝试了上述方法,但出现数据库错误,抱怨子表中的外键字段不能为 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?

提前致谢.

推荐答案

我尝试了上述方法,但出现数据库错误,抱怨子表中的外键字段不能为 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 约束)

First, you need to cascade the save operation (but my understanding is that you are doing this or you wouldn't get a FK constraint violation during inserts in the "child" table)

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

Second, you probably have a bidirectional association and I think that you're not setting "both sides of the link" correctly. You are supposed to do something like this:

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);

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

A common pattern is to use link management methods:

@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);

参考

  • Hibernate 核心参考指南
    • 1.2.6.工作双向链接
    • 这篇关于使用 JPA Hibernate 自动保存子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆