2017-08-24 67 views
2

我想其中有孩子实体的集合(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

+0

你如何保存你的实体 –

+0

'em.persist(新父());' 我省略了一些给定的细节(id,entitymanager,...) –

+1

你可以分享你的服务 –

回答

0

唯一的例外是指的节约临时实体,这意味着你要保存它与非托管实体关系实体,因为你的父母是级联onetoone孩子那么问题将与childHistory,因为这是一个双向的关系,这将使因为级联孩子也

@OneToMany(mappedBy = "parent",cascade=CascadeType.PERSIST) 
private List<Child> childHistory; 
+0

不是问题 - 错误不是NRE。现在在问题中修复。 –

+0

@ jl.try现在这应该工作 –

+0

我会尝试拿出一个示例项目。无论我如何在级联中移动,我都无法解决问题。 –