I have recently had a problem doing a big cascading delete, thread here:
http://forum.hibernate.org/viewtopic.php?t=927292&highlight=
What it turned out to be is the order that properties were declared in the mapping files.
Here is a mapping that wouldn't work:
Code:
<class name="my.model.MasterItem" table="MasterItem">
<id name="id" unsaved-value="null">
<generator class="uuid.hex" />
</id>
<set
name="subItems"
lazy="true"
inverse="false"
cascade="all"
sort="unsorted">
<key column="masterId" />
<one-to-many class="my.model.SubItem"/>
</set>
<set
name="sharedItems"
lazy="false"
inverse="false"
cascade="all"
sort="unsorted">
<key column="masterId" />
<one-to-many class="my.model.SharedItem" />
</set>
</class>
<class name="my.model.SubItem" table="SubItem">
<id name="id" unsaved-value="null">
<generator class="uuid.hex" />
</id>
<set
name="sharedItems"
table="SubShareds"
lazy="false"
inverse="false"
cascade="none"
sort="unsorted">
<key column="subId" />
<many-to-many class="my.model.SharedItem" column="sharedId" />
</set>
</class>
<class name="my.model.SharedItem" table="SharedItem">
<id name="id" unsaved-value="null">
<generator class="uuid.hex" />
</id>
<property name="name" type="java.lang.String" column="name" not-null="false" unique="false" />
</class>
The important part is the order that the SharedItem's and SubItem's are referred to in the MasterItem. The reason this fails is that on deleting the MasterItem, it first finds the SubItem's and loads into the session all the objects that it refers to, which includes some SharedItem's. However, it can't delete the SharedItem's because they are owned by the MasterItem and only it has the cascade delete on it.
Then, the SharedItem's are loaded on the MasterObject and it tries to delete them, but fails because the same objects are already loaded in the same session.
Changing the class defintion as follows fixes this problem.
Code:
<class name="my.model.MasterItem" table="MasterItem">
<id name="id" unsaved-value="null">
<generator class="uuid.hex" />
</id>
<set
name="sharedItems"
lazy="false"
inverse="false"
cascade="all"
sort="unsorted">
<key column="masterId" />
<one-to-many class="my.model.SharedItem" />
</set>
<set
name="subItems"
lazy="true"
inverse="false"
cascade="all"
sort="unsorted">
<key column="masterId" />
<one-to-many class="my.model.SubItem"/>
</set>
</class>
My question is, have I just got my data structure or mappings wrong, or is this the expected behaviour?
Thanks!