- Store the old class loader (OSGi container)
- Set the new class loader (e.g. the standard class loader)
- Create an Entity Manager Factory
- Restore the class loader to the original (OSGi Container)
EntityManagerFactory emf = null;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.
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);
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.
0 kommentarer:
Skicka en kommentar