我在父表和子表之间有一对多的关系。在父对象中我有一个
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);
引用
- Hibernate 核心引用指南
关于java - 使用 JPA Hibernate 自动保存子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3927091/