2012-01-12 68 views
0

我有兩個類,ProductConfiguration和SubProduct。休眠和從列表中刪除

我要替換的配置中的子產品,我這樣做:

productConfiguration.getSubProducts().clear(); 
productConfiguration.getSubProducts().addAll(newSubProducts); 

在這一過程中,Hibernate的嘗試設置父(產品配置)爲空的ID,並然後更新數據庫中的行。這會失敗,因爲父ID是外鍵,因此不能爲空。

從ProductConfiguration映射到子產品:

<bag name="subProducts" 
    table="sub_product" 
    cascade="all-delete-orphan" 
    access="field" 
    lazy="false"> 
    <key column="parent_id"/> 
    <one-to-many class="com.conscius.cpt.core.product.SubProduct"/> 
</bag> 

<many-to-one name="parentProduct" 
      class="com.conscius.cpt.core.product.ProductConfiguration" 
      column="parent_id" 
      access="field" 
      not-null="true" 
      cascade="none"/> 
+1

當子產品被刪除時,您是否打算將子產品存在於數據庫中?如果沒有,看看這個:http://docs.jboss.org/hibernate/core/3.3/reference/en/html/example-parentchild.html#example-parentchild-bidir – zmf 2012-01-12 15:13:28

+0

我看到我錯了什麼地方。我錯過了ProductConfiguration一側的逆向語句。我會盡快添加答案。 – SimonPip 2012-01-12 15:26:50

回答

0

這裏的解決方案是si mple。我忘了在產品配置一側添加一個反向語句。

<bag name="subProducts" 
    table="sub_product" 
    cascade="all-delete-orphan" 
    access="field" 
    lazy="false"> 
    <key column="parent_id"/> 
    <one-to-many class="com.conscius.cpt.core.product.SubProduct"/> 
</bag> 
1

如果外鍵不可爲空,你可能想要刪除它沒有父子產品:

<bag name="subProducts" cascade="all-delete-orphan" ... 

更新:防止更新你可以做的外鍵

<bag name="subProducts" inverse="true" ... 

// and 
for (SubProduct sub : productConfiguration.getSubProducts()) 
{ 
    sub.setParentProduct(null); 
} 
productConfiguration.getSubProducts().clear(); 
productConfiguration.getSubProducts().addAll(newSubProducts); 
+0

是的,對不起,我確實有過這種情況,但認爲這可能是問題所在。它不是,我已經重新插入了刪除孤立部分。 – SimonPip 2012-01-12 15:28:35