我try 了上述操作,但收到数据库错误,报告Child表中的外键字段不能为空.有没有一种方法可以告诉JPA将这个外键自动设置到Child对象中,这样它就可以自动保存子对象呢?
这里有两件事.
首先,您需要级联save操作(但我的理解是,您正在这样做,否则在"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