Tuesday, November 13, 2007

Hibernate won't delete child objects from database

Given a commonly known parent/child relationship in a domain model, the hibernate code below would not delete child object from database.
Parent p = (Parent)session.load(Parent.class, id);
Child c = p.getChildren(0);
p.getChildren().remove(c);
c.setParent(null);
Unless you have specified 'all-delete-orphan' as the cascade value in the relation as shown below, or use 'Session' object to delete the object from db.
<set name="children" inverse="true" cascade="all,delete-orphan">
<key column="parent_id">
<one-to-many class="Child">
</set>
This detail is from hibernate manual (Section 21.3), and I have read it many times in last three years, but somehow I didn't find it intuitive thing to do and hence drawing a blank.

It's a breeze to have 'Session' object available everywhere in the code, but imagine a pile of layers hiding everything related to persistence, all you can do is play around with associative object references in the object graph.

There are many such minute intricacies in Hibernate which give surprises (and pain if that code is not covered by test cases), Endless debugging with hibernate is just as painful as dear old CMP (Container managed persistence in Entity Beans). Ironically though, Hibernate can win the "paingiving" if you use it with cglib whereby, while debugging, you see weird things in lazily loaded proxy (or object zombie if you like to call it so) where you wanted to see only a string value.

And oh I hate that AbstractEntityPersister.java with it's 4000 lines of code...

4 comments:

Kiran Bhagwat said...

Thanks a lot Nirav...
you solved my million dollar problem. :)

Unknown said...

Thanks this helped me as well!

vic said...

Thank you!!
And it is "all-delete-orphan". In the hbm.xml you have "all,delete-orphan"

Anyway... Thank you!

Anonymous said...

many many thanks!