Hibernate lazy=false affects deletion
I'm trying to set up a project using hibernate.I have two tables : Users and Address with the following mappings :
<?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>
If I set lazy=false I get an error on deletion : deleted object would be re-saved by cascade
and I set lazy=true then I won't be able to access my objects due to lazy initialization errors.
Any help is appreciated.
Thx.
You need to remove Usr
from the corresponding Address.usrs
before removing it from the database. Otherwise Hibernate tries to re-save it by cascading, since usrs
is configured as cascade="all-delete-orphan"
.
With lazy = "true"
you don't have this problem since cascading is not applied to uninitialized lazy collections.
Also, declaring all relationships as eager is not always a good solution for lazy initialization problems. Other possible solutions include Open Session in View pattern and fine-grained fetch strategy tuning with join fetch
and so on.
精彩评论