You aren't the only person facing this problem!!! I have been searching for a way to add
ON DELETE CASCADE DDL to HBM generated DDL for days, with no luck.
This should be a very straightforward process, seeing it is a basic requirement of any RDBMS. Below I have a mapping of a class which has a set of objects which refer back to the same class, a sub-group in this case. Notice the
on-delete setting
childGroups key.
According to the hibernate docs, this should generate
ON CASCADE DELETE DDL, or at least that is how I am reading it. By adding
cascade="delete", a distinct
delete sql command is being generated, which I find unnecessary. One would think that a single delete for the parent would suffice if the proper
ON DELETE CASCADE were being generated by hbmddl.
What is actually happening is the delete sql commands are working fine until the last one executes, which is the one which deletes the parent row. Seeing this is being run in a single transaction, I suspect that somehow the Session thinks these objects are still persistent when in fact they have already been deleted.
Code:
<hibernate-mapping>
<class name="com.xrite.ind.core.Group" table="tblGroup" >
<id name="Id" type="long">
<column name="groupID" />
<generator class="native" />
</id>
<property name="name" column="name" lazy="false" length="50" type="string" not-null="true" unique="false" index="IDX_GROUP_NAME" />
<set name="standards" lazy="true" cascade="save-update" inverse="true" order-by="name" >
<key column="groupID" on-delete="cascade"/>
<one-to-many class="com.xrite.ind.core.Color" />
</set>
<many-to-one name="parent" class="com.xrite.ind.core.Group" lazy="false" index="group_parent_idx" >
<column name="group_parent_id" />
</many-to-one>
<!-- cascade="delete-orphan" -->
<set name="childGroups" lazy="true" inverse="true" order-by="name" cascade="delete" >
<key column="group_parent_id" on-delete="cascade"/>
<one-to-many class="com.xrite.ind.core.Group"/>
</set>
</class>
</hibernate-mapping>