2014-09-24 73 views
0

这里有一些奇怪的事情发生在hbm.xml实现上。
父映射Hibernate:一对多非空属性引用空值或瞬态值

<list name="children" inverse="true" lazy="true" cascade="all"> 
    <key> 
     <column name="parent_id" not-null="true"/> 
    </key> 
    <list-index column="sequence"/> 
    <one-to-many class="Child"/> 
</list> 

儿童映射

<many-to-one name="parent" class="Parent" cascade="all"> 
    <column name="parent_id" not-null="true"/> 
</many-to-one> 

异常

"not-null property references a null or transient value: Child.parent" 

子类

public class Child { 
    private Parent parent; 

    //parent getter and setter 
} 

使用Hibernate 4.0

回答

0

当你通过Child对象session.save()Child对象有parent = null您收到此异常。

很常见的,并建议图案是在父类中使用这样的便利方法:

Parent.java

public void addChild(Child c) { 
    if (children == null) { 
     children = new ArrayList(); 
    } 

    children.add(c); 
    c.setParent(this); 
} 

// make setter private 
private void setChildren(List<Child> children) { 
    this.children = children; 
} 

私人设定器setChildren将在内部由Hibernate使用。

当您构建/修改您的Parent对象时,应该使用addChild方法。

+0

'addChild(Child c)'会被hibernate使用吗?或者我需要从一些setter调用它? – 2014-09-24 19:30:14

+0

我刚刚编辑答案,使其更加清晰 - addChild是你方便的方式将孩子追加到儿童收藏。 Setter可能是私有的,以确保只有休眠才会使用它。 – 2014-09-24 19:40:44

+0

'setChildren()'正在被其他类使用,所以我不能将它改为'private'。但我确实改变了setChildren()为每个“Child”设置“Parent”。 – 2014-09-24 20:12:34

相关问题