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”/>
</set>

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();

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

session.saveOrUpdate(a);
session.flush();

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!

bytecode editor saved the day

Happy new year!

I had a tough simple problem that requires me to change a string in java class. Of course, I don’t have the source code for it. Normally, I would just use decompiler to get the java source and change and recompile. Easy right? this time, the class is so strange in some way that none of the decompilers I used got me a good java code. This is a first time for me. Usually, frontend plus or DJ or Java decompiler do the job really nicely. This time, the java code always had strange codes and lots of labels (remember those Java labels?) anyway, I googled to find those might be related to the fact the original class has a lot of try-catch blocks either stacked or enclosed.  I didn’t want to mess up the java code since I am afraid to introduce bugs into the class. All I wanted to do is to change a string constant which prevented the program from running correctly during network connection (it is a http call class).

So for the first time, I resorted to bytecode editor, which I had only heard of before. After spending a few hours and good size of frustrations, I found cafebabe allowed me to edit that string and save the class file. Hurray! problem solved right away after I injected the new doped class to the original jar file.

Thanks, Cafebabe – http://sourceforge.net/projects/cafebabe

Tony