【发布时间】:2018-02-02 07:11:07
【问题描述】:
我正在尝试建模一个父实体,该实体具有一组子实体 (childHistory) 以及指向最后添加的子实体 (currentChild) 的指针
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>]])不可为空 协会:([com.Child.entity])
警告:HHH000437:尝试保存一个或多个具有 与未保存的瞬态实体的不可空关联。未保存的 在保存这些临时实体之前,必须将其保存在操作中 依赖实体。未保存的临时实体:
([com.Child#<null>])依赖实体:([[com.Parent#<null>]])不可为空 协会:([com.Parent.currentChild])
有没有一种方法可以正确地对此进行建模,并且在休眠时使用 NOT NULL db 列。
编辑:有关重现,请参阅此要点:https://gist.github.com/jlogar/2da2237640aa013f2cfbda33a4a5dc84
【问题讨论】:
-
如何保存实体
-
em.persist(new Parent());我省略了一些给定的细节(id,entitymanager,...) -
你能分享你的服务吗
-
“我不明白这一点。”关键是它将清楚地显示问题的根本原因,即您在保存之前没有设置双向关系的双方。 stackoverflow.com/questions/26219099/…
-
我已经更新了问题的要点以重现该问题。