05 November 2008

Hibernate and OSGi: The problem

Making Hibernate work in an OSGi environment is not trivial. Over the last couple of months, I have been experimenting with various approaches, and I'm not yet fully satisfied with the solutions I have found.

The funny thing is, there must be a whole bunch of people facing the same problem, and you do find a couple of postings or example code with the help of your favourite search engine, however, none of the articles or examples seem to match my environment or my requirements.

Now here is an outline of my approaches, which may or may not work for you. Take a look and give me some feedback.

Before talking about the solutions, we all know the answer is 42, but we haven't really worked out the question yet, so let me first list the issues you have to deal with:
  • Hibernate has a lot of third-party dependencies.
  • When you use an XML configuration file for your session factory, Hibernate must be able to load ist.
  • Hibernate needs to load your JDBC driver classes.
  • When using Hibernate mapping files for your entity classes, Hibernate needs to be able to load them as resources.
  • While processing the mapping files, Hibernate reads the names of your entity classes and loads them using Class.forName().
  • Hibernate internally uses ANTLR to parse HQL queries, and it passes a custom token class to ANTLR. Unfortunately, ANTLR requires you to specify this class by name and uses Class.forName() load the custom token class.
  • When using lazy loading with the CGLIB proxy generator, Hibernate injects a dependency on CGLIB into your model classes. Thus, any bundle using you model classes may have to load CGLIB classes.
There may be more issues, depending on the way you work with Hibernate. In my project environment, some issues mentioned by other people simply do not occur, while others lead to new problems.
  • We do not use Hibernate annotations.
  • Our OSGi configuration is static. All bundles are installed and started during the framework startup phase, registering all services. We do not have to worry about adding new classes to the session factory when a bundle gets installed at run-time. (For this reason, the extender pattern approach is a bit too heavyweight for my taste.)
  • We do not use a web container, or Spring, or anything else, just naked OSGi - well, Eclipse Equinox, in fact.
  • Our IDE is Eclipse and we want to be able to launch our OSGi application including Hibernate from Eclipse.
  • We also use Eclipse PDE batch builds.
Having described to problem in some detail, I will explain a pragmatic and a more elaborate solution in separate articles.

1 comment:

Mike Van said...

hey there. If you'd like more information on making Hibernate work in OSGi, specifically Karaf, check out my blog at http://os-tech.blogspot.com/.