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”/>
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 session.save(A). 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();
Set Bs= a.getBs();
Iterator iter = Bs.iterator();
B b= (B) iter.next();
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!