Eclipselink: How do you get EntityManager in each bundle?

I am wondering how to create an EntityManager in every Bundle. Or how to use JPA in OSGi.

In fact, I have one main package that loads the persistence.xml file and creates an EntityManager instance. After that, my main package gives an instance of the Entity manager to other packages through services. Therefore, I use the capabilities of the equinox services, and I am sure that there must be one more solution for getting the EntityManager in each bundle!

Do you know another solution? or the right way to achieve this?

+6
jpa eclipselink persistence osgi
source share
2 answers

You looked at JPA OSGi examples on the EclipseLink wiki: http://wiki.eclipse.org/EclipseLink/Examples/OSGi

EclipseLink is packaged and designed to run on OSGi. And in the near future, Eclipse Gemini JPA will add support for using EclipseLink through the new OSGi JPA standard (www.eclipse.org/gemini/jpa, Stackoverflow will not allow me to publish the full URL). I think you will like Gemini JPA, since the specification is very service oriented and EntityManagerFactory can be obtained through services from any package. We are working on the initial milestone for JPA Gemini, so for now I stick with EclispeLink OSGi.

- Shaun

+3
source share

If you are writing a desktop application (and therefore do not have access to save containers), I suggest you publish the EntityManageFactory as a service, not an EntityManager. Then your code will have this layout:

public void someBusinessMethod() { EntityManager em = Activator.getEntityManager(); try { ... } finally { em.close(); } } 

And in your activator:

 public class Activator implements BundleActivator { private static ServiceTracker emfTracker; public void start(BundleContext context) { emfTracker = new ServiceTracker(context, EntityManagerFactory.class.getCanonicalName(),null); emftracker.open(); } public void stop(BundleContext context){ emfTracker.close(); emfTracker = null; } public static EntityManager getEntityManager() { return ((EntityManagerFactory)emfTracker.getService()).createEntityManager(); } } 

Hope this helps you give you an idea.

+3
source share

All Articles