Search code examples
hibernatepersistenceosgi

OSGi + Hibernate


Instead of having database actions scattered in four (osgi) bundles, all doing there slightly different things. I want to create a (simple) OSGi bundle that is responsible for all persistance issues. I feel that this is not as simple as it sounds because of the "unique classloader per bundle" thing. So what I really would appreciate is if someone knows the solution(s) to this kind of problem.


Solution

  • (If you are using Hibernate Annotations)

    Save all the Entities class loaders when the Hibernate bundle is informed about an annotated class.

    Then do something like this before building your SessionFactory.

    ClassLoad cl = Thread.currentThread().getContextClassLoader();
    try {
     Thread.currentThread().setContextClassLoader(yourClassLoader);
     factory = cfg.buildSessionFactory(); 
    }finally {
     Thread.currentThread().setContextClassLoader(cl);  // restore the original class loader
    }