I have 2 objects Parent and Child associated with a one to many mapping.
Now I want to delete all the childs of Parent.
I used the following code but it does not have any effect.
//start tx
Parent p = getFromDb();
p.setChilds(null) ; explicitly setting to null so that childs get deleted
session.merge(p);
//commit tx
I have the following in my configurations:
<set name="myChilds" inverse="true" lazy="false" cascade="all">
<key>
<column name="parentId" />
</key>
<one-to-many class="com.xyz.MyChild" />
</set>
Am not getting any exception but childs not get deleted.
The
myChildscollection is marked as the inverse association of the many-to-one from child to parent. This means that Hibernate uses the other side of the association to decide if the association exists or not.You should thus set the
child.parenttonullrather than nulling (or emptying, which is much cleaner than nulling) the set of children.This, however, won’t be sufficient. Breaking an association between a parent and its children doesn’t kill the children. It just makes them orphan. If you want to delete them, you must call
session.delete()on every child.Finally, merge is not useful at all here. The goal of merge is to copy the state of a detached entity to its attached version. Your parent entity is already attached.
You seem to have missed many parts of the very good explanations in the Hibernate reference documentation. Read it again.