hibernatehibernate-mappinghbmhibernate-onetomanybidirectional-relation

Hibernate Mapping : delete children in one to many bidirectional mapping in hibernate


I have a parent object and its detail object. The mappings are mentioned in the below code -

Parent Object Mapping

    <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class lazy = "false" name="com.test.model.Parent" table="parent">
        <id name="parentId" column="PARENT_ID" type="long">
            <generator class="sequence">
                <param name="sequence">PARENT_ID_SEQ</param>
            </generator>
        </id>
        <set 
            name="childSet" 
            lazy="false" 
            cascade="all-delete-orphan" 
            inverse="true" 
            table = "child" 
            order-by = "CHILD_ID"
            >
            <key column="PARENT_ID"/>
            <one-to-many class="com.test.model.Child"/>
        </set>
    </class>
</hibernate-mapping>

Child Object mapping

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.test.model.Child" table="hot_Cash_coupon">
        <id name="childId" column="CHILD_ID" type="long">
            <generator class="sequence">
                <param name="sequence">CHILD_ID_SEQ</param>
            </generator>
        </id>
        <many-to-one name="parent"
            class="com.test.model.Parent" column="PARENT_ID" not-null="true" />
    </class>
</hibernate-mapping>

I am able to save a new parent with say 3 childrens. Now, in the update operation,

In parent.childSet, I am removing all values and setting new values. When I do session.update(parent), my requirement is to,

  1. Delete all the existing children for the parent - as the parent.childSet doesn't have them.
  2. Insert the new values that are available in parent.childSet.

here, parent.childSet means, the Set in Parent Class/HBM Mapping.

The problem happening now is,

  1. It is throwing exception - "cannot insert NULL into ("CHILD"."PARENT_ID")"

I will keep updating the question if it is not clear.

Thanks for your time!


Solution

  • For the time being I am doing an session.update(parent). Which nullify the foreign keys and orphan records exist in the CHILD table. And there after I do a session.delete(...) of the orphans manually.

    This is more of a workaround than a solution.