How-(not-)to use Hibernate

Digging into some legacy code, I found the worst way to initialize Hibernate. The first step should be something like:

Configuration cfg = new Configuration();
cfg.addClass(Bean1.class)
   .addClass(Bean2.class)
   .addClass(Bean3.class);

But I found this:

Configuration cfg = new Configuration();
Object[] objs = new Object[] {
    new Bean1(), new Bean2(), new Bean3()
};
for (int i = 0; i < objs.length; i++)
    cfg.addClass(objs[i].getClass());
}

You only need to know the basics of Java to find out the waste of memory and CPU, instantiating a lot of classes (and an array) only to get the class instantiated. And, of course, the unnecessary loop to iterate over the array. It’s like baking a cake to find out the brand of the flour.

As if it’s not enough, this piece of code is replicated in about 7 spots. Yes, the right way to configure Hibernate is using the “HibernateUtils” pattern, as in documentation.

And, as if it’s not enough yet, this piece of code creates a SessionFactory that is sent via constructor to an entire hierarchy of classes. Yes, it is the worst solution, since the Session creation could be on HibernateUtils (as in documentation, again).

Tags: , ,

One Response to “How-(not-)to use Hibernate”

  1. Gaeta Windows XP Mozilla Firefox 2.0.0.11 Says:

    There is a long way to became a grown up, from being a small kid…

Leave a Reply