我有一个关于从小孩的entites IR 引用ParentEntities问题,如果我有这样的事情:JPA @OneToMany - >父 - 子引用(外键)
Parent.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:
id
100
Child
id paren_id
101 (null)
因为我还没有家长设置为儿童。所以我的问题:
我真的必须做某事。喜欢这个?
Parent.java:
...
setChildren(Set<Child> children) {
for (Child child : children) {
child.setParent.(this);
}
this.children = children;
}
...
编辑:
根据快速回复我能够通过使用基准拥有实体的@JoinColumn来解决这个问题。如果我们从上面看例子,我做了某事。像这样:
Parent.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);
}
引用是正确的设置父母:
Parent:
id
100
Child
id paren_id
101 100
感谢您的答复。
**您是否有父项子项实体?**如果是,他们是如何配置的。没有父母我得到错误(_StaleStateException:批量更新返回来自update [0]的意外行数;实际行数:0;预期:1_)。如果我添加没有注释的父项,它也会显示错误(映射错误)。在child的父字段上设置@manytoone,我在保存时出错(_ORA-00904:“REPORT_REPORT_ID”:недопустимыйидентификатор_)。我的fk和它的pk上的id命名为report_id,但我不知道report_report_id在哪里。 – Erlan 2015-08-07 05:11:01
(使用EclipseLink JPA实现)。值得注意的是你仍然需要@Column(name =“paren_id”)private long parenId;绘制你的孩子这个工作。 – AfterWorkGuinness 2015-09-23 14:57:20