2011-04-13 104 views
0

我試圖用hibernate.I建立一個項目有兩個表:用戶和通過以下映射地址:休眠懶惰=假影響刪除

<?xml version="1.0"?> 
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<!-- 
    Mapping file autogenerated by MyEclipse - Hibernate Tools 
--> 
<hibernate-mapping> 
    <class name="Address" table="ADDRESS" > 
     <cache usage="read-write"/> 
     <id name="addressId" type="long"> 
      <column name="ADDRESS_ID" precision="22" scale="0" /> 
      <generator class="increment" /> 
     </id> 
     <property name="street" type="string"> 
      <column name="STREET" length="50" /> 
     </property> 
     <property name="city" type="string"> 
      <column name="CITY" length="20" /> 
     </property> 
     <set name="usrs" inverse="true" cascade="all-delete-orphan"> 
      <key> 
       <column name="ADDRESS_ID" precision="22" scale="0" not-null="true"/> 
      </key> 
      <one-to-many class="Usr" /> 
     </set> 
    </class> 


</hibernate-mapping> 

<?xml version="1.0"?> 
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<!-- 
    Mapping file autogenerated by MyEclipse - Hibernate Tools 
--> 
<hibernate-mapping> 
    <class name="Usr" table="USR" > 
     <cache usage="read-write"/> 
     <id name="usrId" type="long"> 
      <column name="USR_ID" precision="22" scale="0" /> 
      <generator class="increment" /> 
     </id> 
     <many-to-one name="address" class="Address" > 
      <column name="ADDRESS_ID" precision="22" scale="0" /> 
     </many-to-one> 
     <property name="logname" type="string"> 
      <column name="LOGNAME" length="20" not-null="true" /> 
     </property> 
     <property name="password" type="string"> 
      <column name="PASSWORD" length="20" not-null="true" /> 
     </property> 
    </class> 

    <query name="Usr.by.city"> 
     <![CDATA[ 
      FROM rUsr as u   
      WHERE u.address.city = :city 
     ]]> 
    </query> 
</hibernate-mapping> 

如果我設置爲lazy =假,我得到一個刪除時出錯: 刪除的對象將被級聯重新保存

我設置了lazy = true,那麼由於延遲初始化錯誤,我將無法訪問我的對象。

任何幫助表示讚賞。

Thx。

回答

1

在將其從數據庫中刪除之前,您需要從相應的Address.usrs中刪除Usr。否則,Hibernate嘗試通過級聯重新保存它,因爲usrs被配置爲cascade="all-delete-orphan"

隨着lazy = "true"你沒有這個問題,因爲級聯不適用於未初始化的惰性集合。

此外,將所有關係聲明爲渴望並不總是解決懶惰初始化問題的好方法。其他可能的解決方案包括Open Session in View pattern以及使用join fetch等進行的細粒度獲取策略調整。

+0

非常感謝axtavt。 – Sergiu 2011-04-13 14:16:50