我想其中有孩子实体的集合(childHistory),也是一个指针,最后添加的孩子(currentChild)映射到一个子表两次 - @OneToMany和@ManyToOne
class Parent {
//unidirectional
@OneToOne(cascade = CascadeType.PERSIST, optional = false)
@JoinColumn(name = "current_child_id")
private Child currentChild;
//bidirectional
@OneToMany(mappedBy = "parent")
private List<Child> childHistory;
public Parent() {
currentChild = new Child(this);
childHistory = new ArrayList<>();
childHistory.add(currentChild);
}
public void add() {
currentChild = new Child(this);
childHistory = new ArrayList<>();
childHistory.add(currentChild);
}
}
class Child {
@ManyToOne(optional = false)
@JoinColumn(name = "parent_id")
private Parent parent;
public Child(Parrent parent) {
this.parent = parent;
}
}
父实体模型
当我尝试保存父级(并依靠级联来坚持子级)时,我目前得到了暂时实体的异常。由于我在Parent ctor中启动了所有内容,因此我无法事先保存Parent。
警告(即导致异常...):
警告:HHH000437:试图保存有未保存的瞬态实体 非空的关联的一个或多个实体。未保存的临时实体必须在保存这些依赖实体之前的操作中保存。未保存的临时实体:
([com.Parent#<null>])
相关实体:([[com.Child#<null>]])
非空的 协会(S):([com.Child.entity])
警告:HHH000437:试图保存有 非空的关联的一个或多个实体与未保存的瞬态实体。未保存的临时实体必须在保存这些依赖实体之前的操作中保存。未保存的临时实体:
([com.Child#<null>])
相关实体:([[com.Parent#<null>]])
非空的 协会(S):([com.Parent.currentChild])
有没有一种方法来正确模拟这一点,并有休眠NOT NULL数据库列。
编辑:对于一个摄制看到这个要点:https://gist.github.com/jlogar/2da2237640aa013f2cfbda33a4a5dc84
你如何保存你的实体 –
'em.persist(新父());' 我省略了一些给定的细节(id,entitymanager,...) –
你可以分享你的服务 –