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

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

问题描述

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

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

List<Child> setChilds(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自动将这个外键设置为Child对象,以便自动保存子对象?

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自动将这个外键设置为Child对象,这样它可以自动保存子对象?

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约束违反, table)

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.setChilds(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.addToChild(c1);

session.save(parent);



参考




  • Hibernate核心参考指南


    • 1.2.6。工作双向链接

    • References

      • Hibernate Core Reference Guide
        • 1.2.6. Working bi-directional links
        • 这篇关于使用JPA Hibernate自动保存子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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