ORM - roll your own or use Hibernate?
As I stated in my last post, I have just finished up a project for school that was done in Java/JSP. For the database, we decided to go with Derby. Because Hibernate does not support Derby and because I thought it would be faster to do with straight JDBC, I decided to fore go Hibernate and create my own database abstraction layer. After all, how hard could it be?
Rod Johnson is right, definitely use some kind of OR mapping tool and never write your own. This I have learned the hard way. After trying to write my own I now know how hard it can be. And this was for a simple application with only a few tables. I can not image how or why anyone would want to do this for a larger application.
There are several things that I found to be difficult in writing my own database layer:
- Resource Management — Dealing with all the different try/catch/finally/try/catch blocks that you need for JDBC is a pain in the neck. And trying to abstract that so that it doesn’t infect the rest of your code is even harder.
- Managing the object graph — Every time I tried to find one object from the database, I ended up having to find several others. In the end, I just loaded the entire object graph—every object—and put them into a cache for easy retrieval. This was better than having to deal with recursive calls to get the next object. This was in part, though, because the app was dealing with trees and linked lists.
- Exceptions — Trying to abstract SQLExceptions was a pain. What I did was to wrap them in another exception and throw that instead. However, this lead to a ton of my exceptions having to get caught in all layers of the code. However, this problem is probably attributed to my lack of experience then to a true problem with JDBC.
My solution to this mess is to either try out some experimental support in Hibernate for Derby or to find an embedded database that is supported by Hibernate. This is the last time I try to write my own database abstraction layer though.