OSGI, JPA

Trying to use JPA in OSGI always gives me the error “javax.persistence.PersistenceException: No Persistence provider for EntityManager named …”. Reason: Persistence.createEntityManagerFactory() uses the ClassLoader to load resources. It seems to be the ThreadContext ClassLoader. So in OSGI it fails due to the OSGI classloader tricks. Using the tricks given in http://lsd.luminis.nl/jpa-persistence-in-osgi-with-openjpa/ I got this to work. That is, the following..

ClassLoader oldCL = Thread.currentThread().getContextClassLoader();

Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());

emf = Persistence.createEntityManagerFactory(“my-persistence-manager”);

Thread.currentThread().setContextClassLoader(oldCL);

And no matter what you do, you get the same error. Even if it never finds the persistence.xml file, or if you typoed tha name in it, or anything else. Oh what a wonderful error message, how informative.

You might think the EclipseLink being the reference JPA implementation you might get proper OSGI consideration but no. After all, it claims to be all OSGIfied. I guess that is no more than export some packages then. And after this fix, Hibernate works for me just as well as, just need to add some exports and manage the dependencies myself. Not a big deal compared to debugging this in the first place.

Advertisement

One thought on “OSGI, JPA

  1. Check out the EclipseLink OSGi examples: http://wiki.eclipse.org/EclipseLink/Examples/OSGi

    OSGi is *not* Java SE and EE and Thread.currentThread().setContextClassLoader is not going to get you very far in any OSGi framework as each bundle has its own classloader. You can hack around this in Equinox with buddy classloading to get Hibernate to work but it isn’t portable and arguably not really OSGi since you’re defeating the modularity that OSGi is built one. But with EcilpseLink OSGi we take care of the necessary classloader magic with no non-portable hacks. Try the examples out. Also, I should point out that there is now an OSGi specification for JPA in OSGi and we’re working on implementing that in the Eclipse Gemini JPA project. We’re not 1.0 yet but we’re working on it. 🙂

    –Shaun

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s