Hibernate lazy = false会影响删除

时间:2011-04-13 13:37:31

标签: hibernate cascade

我正在尝试使用hibernate设置项目。我有两个表:Users和Address,带有以下映射:

<?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 = false,我会在删除时收到错误: 已删除的对象将由级联

重新保存

并设置lazy = true然后由于延迟初始化错误,我将无法访问我的对象。

感谢任何帮助。

THX。

1 个答案:

答案 0 :(得分:1)

在将数据库从数据库中删除之前,您需要从相应的Usr中删除Address.usrs。否则,Hibernate会尝试通过级联重新保存它,因为usrs配置为cascade="all-delete-orphan"

使用lazy = "true"您没有此问题,因为级联不会应用于未初始化的惰性集合。

此外,将所有关系声明为渴望并不总是解决延迟初始化问题的好方法。其他可能的解决方案包括Open Session in View pattern和使用join fetch的细粒度获取策略调整等等。