When using OpenJPA with a OSGi container like Felix you will get into some class loading troubles because OpenJPA will not be able to create an Entity Manager. It need to bypass the OSGi container’s class loader and this is how you do it.

  1. Store the old class loader (OSGi container)
  2. Set the new class loader (e.g. the standard class loader)
  3. Create an Entity Manager Factory
  4. Restore the class loader to the original (OSGi Container)

You can put your code into the start() method of your BundleActivator:

EntityManagerFactory emf = null;
ClassLoader oldCL = Thread.currentThread().getContextClassLoader();        Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());

Map<String, String> props = new HashMap<String, String>();
// Create a Properties object with connectio parameters for database
props.put(“javax.persistence.provider”, “org.apache.openjpa.persistence.PersistenceProviderImpl”);
props.put(“openjpa.ConnectionURL”, database_url);
props.put(“openjpa.ConnectionDriverName”, database_driver);
props.put(“openjpa.ConnectionUserName”, database_user);
props.put(“openjpa.ConnectionPassword”, database_password);
props.put(“openjpa.jdbc.SynchronizeMappings”, “buildSchema”);

emf = Persistence.createEntityManagerFactory(“PERS_UNIT”, props)

// Change it back to the old classloader when everything is initialized.
Thread.currentThread().setContextClassLoader(oldCL);

 When you have created the entity manager and restored the classloader you can now use the EntityManagerFactory to create an EntityManager and start to use it.
It is important that you do this after you have restored the classloader or you will get conflicts between classes e.g if you have used an interface and created the class in one module and sent it to another module, the system will complain about that the class was created with another class loader.