2011-03-04 108 views
3

我有很多-to-many關聯等被定義:Hibernate:部分延遲初始化?

Parent.hbm.xml:

<set name="children" table="child_parent_map" lazy="true"> 
     <cache usage="nonstrict-read-write" /> 
     <key column="parent_id" /> 
     <many-to-many class="Child"> 
      <column name="child_id" not-null="true" index="child_parent_by_child"/> 
     </many-to-many> 
    </set> 

Child.hbm.xml:

<set name="parents" table="child_parent_map" lazy="true"> 
     <cache usage="nonstrict-read-write" /> 
     <key column="child_id" /> 
     <many-to-many column="parent_id" class="Parent" lazy="false"/> 
    </set> 

相當肯定我正在初步化Parent.children步行集合。例如:

for(Child child : parent.getChildren()) { 
    Hibernate.initialize(child.getAnotherProperty()); 
} 

父母有六個孩子。然而,在一個會話中,父母似乎只有五個,而在另一個會話中(2秒後,數據庫或另一個會話中沒有任何變化) - 全部六個。實際上,我在將這些實體從自定義克隆器中分離出來之後發現它。

我認爲懶惰的集合要麼被完全初始化(即所有的元素都是),要麼不是。不知何故,只有部分藏品可以初始化?它可能是緩存問題嗎?

編輯:此會話處理一個相當大的數據集(幾千個實體)。這是否有可能是因爲一些已經加載的實體從會話中被驅逐出來?

+2

你給屬性「default_batch_fetch_size」設置了一些值嗎? – jpkrohling 2011-03-05 07:57:56

+1

你可以發佈父母和孩子的代碼嗎?我會先看看hashCode()和equals()。 – 2011-03-07 21:13:12

+0

Michal是對的,你可能在hashCode()和/或equals()中引起了你的對象行爲異常。 – 2011-03-08 11:06:58

回答

1

開始通過檢查你的的hashCode()的equals()方法,不正確地執行這些方法經常會導致這種行爲。