Monday, October 08, 2007

The art of not repeating yourself

I discovered a great bug in the my code today, It was weird hibernate related bug. If you have been working with hibernate enough you know you've to be careful about the ordering of statements relating to your persistent object model, that may sound little odd but that's how it is with hibernate. If you hit the SQL constraint exception and you've multiple joined entities, be cautious, you might want to isolate call to some many-to-one references earlier than populating your domain object.

There are several ways you'll force flush to hibernate session and that flush (a flush can be a batch update) will cause DB validation and if that flush happens before statements that set the non-null fields, you'll be greeted with boring exceptions. They are not very interesting exceptions to deal with and it might take sometime before you understand what's going on. In general, debugging hibernate code is never interesting unless you've less experience with some outstanding ORM patterns.

The problem that I hit today was slightly different than what I described though (but I've experienced similar problems many times), My problem was that I was inadvertently modifying a read-only row which had 'long' primary key with '0L' as value, if you've worked enough with hibernate types you know 0 (zero) is the default value for long and integer types. It is just because I was modifying that row by mistake hibernate decided to save that row with different primary key (new sequence number), it assumed 0(zero) as default value (dirty value in Identity Map) for long primary key type, this is bad assumption but there are less ways any ORM framework can find dirty objects. So from next time onwards be aware about these little details If you hit problem of similar nature.

How I prevented myself from repeating was the way of writing a simple JUnit test case which isolated the problem in my code and pointed me to the place where I should be looking without long (very very long) J2EE debugging session. Let me tell you, that's great relief! With that test case I was able to refactor the code and resolve this bug without too much pain. Which makes me and my manager happy :)

If you've been experimenting something similar, I would be glad to know..

No comments: