Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eclipselink : How do you get the EntityManager in each bundle?

I wonder about a good way to have an EntityManager in each Bundle. Or how to use correctly JPA in an OSGi program.

Actually, I've one main bundle that loads the persistence.xml file and instantiates the EntityManager. After, my main bundle gives the instance of Entity manager to the other bundles via the services. So I use the power of the services of equinox and I'm sure it must exist an another solution to obtain an EntityManager in each bundle!

Do you know an another solution? or a correct way to achieve this?

like image 898
user376112 Avatar asked Jul 13 '10 13:07

user376112


2 Answers

Have you taken a look at the JPA OSGi examples on the EclipseLink wiki: http://wiki.eclipse.org/EclipseLink/Examples/OSGi

EclipseLink is packaged for and designed to work in OSGi. And coming soon is Eclipse Gemini JPA which adds support for using EclipseLink through the new OSGi JPA standard (www.eclipse.org/gemini/jpa, Stackoverflow won't let me post the full URL). I think you'd like Gemini JPA as the spec is very service oriented and an EntityManagerFactory may be obtained via services from any bundle. We're working towards an initial milestone for Gemini JPA so for now I'd stick with EclispeLink OSGi.

--Shaun

like image 169
Shaun Smith Avatar answered Oct 04 '22 22:10

Shaun Smith


If you are writing a desktop application (and hence don't have access to container-manages persistence), I suggest you publish the EntityManageFactory as a service, and not the EntityManager. Your code will then 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 to give you an idea.

like image 20
Tassos Bassoukos Avatar answered Oct 04 '22 23:10

Tassos Bassoukos