The @Multitenant support in Eclipselink 2.3 looks really interesting, but I’m having a hard time understanding how to use it in a JSF or EJB which injects an EntityManager with @PersistenceContext. The EclipseLink docs are pretty clear that @PersistenceContext injection doesn’t work in this case, but you could inject an EntityManagerFactory via @PersistenceUunit instead.
Still, what I’m not seeing is how to manage the lifecycle of an EntityManager you might create via injected EntityManagerFactory.createEntityManager() – in particular, when to close the resulting EntityManager, and how to participate in transactions.
Has anyone gotten this to work? Or am I missing something obvious?
See also: http://wiki.eclipse.org/EclipseLink/Examples/JPA/Multitenant
UPDATE
I had some success with @PersistenceContext (EntityManager) injection and then passing parameters to EclipseLink via session listener. I’m not 100% sure this is the right answer and would appreciate confirmation that it isn’t creating a non-obvious race condition or thread-safety issue.
For example:
public static class TenantListener extends SessionEventAdapter {
@Override
public void postAcquireClientSession(SessionEvent event) {
long tenantId = **business logic**;
event.getSession().setProperty("eclipselink.tenant-id", tenantId);
}
}
Using events is fine.
You could also inject the EntityManager and set the property, or inject the EntityManagerFactory and use joinTransaction() to join the active JTA transaction.