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 manag开发者_高级运维er 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?
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
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.
精彩评论