Take the 2-minute tour ×

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


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 {

    public void postAcquireClientSession(SessionEvent event) {
        long tenantId = **business logic**;
        event.getSession().setProperty("eclipselink.tenant-id", tenantId);
share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

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.

share|improve this answer
Thanks. Am I understanding correctly that a "client session" is scoped to a single transaction or operation, so I don't need to worry about tenant leakage to another thread? I think the session event listener will work best. There isn't always a single obvious place to set properties on an injected EntityManager, and the thought of using an EMF and having to have finally { em.close(); } everywhere is unappealing. –  wrschneider99 Oct 21 '11 at 1:45
add comment

Your Answer


