我正在尝试对具有子实体集合 (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;
}
}
当前,当我尝试保存父级(并依靠级联来持久化子级)时,我得到了 transient 实体的异常。我无法事先保存 Parent,因为我在 Parent ctor 中初始化了所有内容。
警告(导致异常...):
WARN: HHH000437: Attempting to save one or more entities that have a non-nullable association with an unsaved transient entity. The unsaved transient entity must be saved in an operation prior to saving these dependent entities. Unsaved transient entity:
([com.Parent#<null>])
Dependent entities:([[com.Child#<null>]])
Non-nullable association(s):([com.Child.entity])
WARN: HHH000437: Attempting to save one or more entities that have a non-nullable association with an unsaved transient entity. The unsaved transient entity must be saved in an operation prior to saving these dependent entities. Unsaved transient entity:
([com.Child#<null>])
Dependent entities:([[com.Parent#<null>]])
Non-nullable association(s):([com.Parent.currentChild])
有没有一种方法可以正确建模并在 hibernate 时拥有 NOT NULL db 列。
编辑:要重现,请参阅此要点:https://gist.github.com/jlogar/2da2237640aa013f2cfbda33a4a5dc84
最佳答案
异常是指保存 transient 实体,这意味着您正在尝试保存与非托管实体有关系的实体,因为您的父级正在级联 onetoone 子级,那么问题出在 childHistory 上,因为这是双向的它会建立关系,因为级联 children 也是
@OneToMany(mappedBy = "parent",cascade=CascadeType.PERSIST)
private List<Child> childHistory;
关于java - 映射到子表两次 - @OneToMany & @ManyToOne,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45860992/