休眠lazy = false会影响删除

问题描述

| 我正在尝试使用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,那么由于延迟初始化错误,我将无法访问我的对象。 任何帮助表示赞赏。 谢谢。     

解决方法

您需要先从相应的
Address.usrs
中删除
Usr
,然后再将其从数据库中删除。否则,由于
usrs
被配置为
cascade=\"all-delete-orphan\"
,Hibernate尝试通过级联重新保存它。 使用
lazy = \"true\"
时不会出现此问题,因为级联不适用于未初始化的惰性集合。 同样,将所有关系都声明为渴望的并不一定总是解决延迟初始化问题的好方法。其他可能的解决方案包括“在视图中打开会话”模式和用ѭ6tuning进行的细粒度访存策略调整等。