2014-09-24 53 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

相關問題