How about some four level cascade one-to-many tables?

Hibernate is your friend when you know more about it. It is not if you don’t …

I have a four level one-many tables. Say A->B->C->D. In A, B, C, there are one-to-many associations. Like this (in A for Set of B objects.)

<set name=”Bs” cascade=”all”>
<key column=”A_id” not-null=”true”/>
<one-to-many class=”B”/>

For insert data in A,B,C,D tables, Fill the object of A with set of B’s, after filling B with set of C’s, after filling C with Set of D’s. Then simply do hibernate All cascading objects will be saved. Great!

Now, how to delete them? Delete from Object A is quite easy, simply do session.delete(a). But I had some trouble deleting from say, B down. It always complains about:

“deleted object would be re-saved by cascade (remove deleted object from associations)…”

It turns out that the message in parens are quite important. You will know if you see the following code:

A a = new A();

session.load(a, 10);
Set Bs= a.getBs();
Iterator iter = Bs.iterator();
while (iter.hasNext()){
B b= (B);


The line iter.remove() is critical to avoid the error message. It actually remove the Child object B from Parent Object A’s B set. So Hibernate will not resave the object B when update Object A’s Set. Well, in this code, all B in Set of B in Object A will be gone. And magically, all Cs in B and Ds in all those Cs are all gone. Thanks, Hibernate!

Happy Chinese New Year!


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s