【发布时间】:2012-03-20 23:29:15
【问题描述】:
我有一个关于从子实体 ir 引用 ParentEntities 的问题 如果我有这样的事情:
父.java:
@Entity(name ="Parent")
public class Parent {
@Id
@Generate.....
@Column
private int id;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "parent")
private Set<Child> children;
simple ... getter and setter ...
}
还有 Child.java:
@Entity(name ="Child")
public class Child{
@Id
@Generate....
@Column
private int id;
@ManyToOne
private Parent parent;
... simple getter an setter
}
将创建以下表格:
Parent:
int id
Child:
int id
int parent_id (foreign key: parent.id)
好的,到目前为止,一切都很好。但是当谈到使用 Java 中的这个参考时,我想,你可以做这样的事情。
@Transactional
public void test() {
Parent parent = new Parent();
Child child = new Child();
Set<Child> children = new HashSet<Child>();
children.add(child);
parent.setChildren(children);
entityManager.persist(parent);
}
这在数据库中导致了这一点:
Parent:
id
100
Child
id paren_id
101 100
但事实并非如此,您必须明确地将 Parent 设置为 Child(我认为,框架可能会自行完成)。
所以数据库中真正的内容是这样的:
Parent:
id
100
Child
id paren_id
101 (null)
因为我没有将父级设置为子级。所以我的问题:
我真的必须做某事吗?像这样?
父.java:
...
setChildren(Set<Child> children) {
for (Child child : children) {
child.setParent.(this);
}
this.children = children;
}
...
编辑:
根据快速回复,我能够通过在引用拥有实体上使用 @JoinColumn 来解决这个问题。如果我们从上面举个例子,我做了某事。像这样:
父.java:
@Entity(name ="Parent")
public class Parent {
@Id
@Generate.....
@Column
private int id;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name= "paren_id")
private Set<Child> children;
simple ... getter and setter ...
}
还有 Child.java:
@Entity(name ="Child")
public class Child{
@Id
@Generate....
@Column
private int id;
... simple getter an setter
}
现在如果我们这样做:
@Transactional
public void test() {
Parent parent = new Parent();
Child child = new Child();
Set<Child> children = new HashSet<Child>();
children.add(child);
parent.setChildren(children);
entityManager.persist(parent);
}
Reference 由 Parent 正确设置:
Parent:
id
100
Child
id paren_id
101 100
【问题讨论】:
-
你的子实体有父级吗?如果有,他们是如何配置的。没有父我得到错误(StaleStateException:批量更新从更新[0]返回了意外的行数;实际行数:0;预期:1)。如果我添加没有注释的父级,它也会显示错误(映射错误)。通过在子项的父字段上设置@manytoone,我在保存时遇到错误(ORA-00904: "REPORT_REPORT_ID": недопустимый идентификатор)。我的 fk 及其在名为 report_id 的 ID 上的 pk 但我不知道 report_report_id 来自哪里。
-
(使用 EclipseLink JPA 实现)。值得注意的是,您仍然需要 @Column(name="paren_id")private long parenId;映射到您的孩子以完成这项工作。
标签: java hibernate jpa parent-child one-to-many