Skip to main content

Notice: This Wiki is now read only and edits are no longer possible. Please see: for the plan.

Jump to: navigation, search


I'd love to see an example of how this would look end-to-end with a container managed environment - i.e., how would you incorporate multitenancy into a managed bean (JSF, EJB etc.) currently using @PersistenceContext?

I suppose you could inject a @PersistenceUnit instead, but then how would you manage the EntityManager lifecycle? @PersistenceContext does it all for you. If you do something like call EntityManagerFactory.createEntityManager(map) in a @PostConstruct method, when do you close it? How does it participate in transactions? etc.

If you set the tenant in the persistence.xml (persistence unit) then there is nothing required. If you are using a shared EntityManagerFactory for all tenants, then you need to set the tenant per transaction. This could be done using setProperty() on the EntityManager as the first operation of the transaction. It could also be done using Session events. I agree a Java EE example would be useful. 12:44, 4 October 2011 (UTC)
I tried setting the tenant with session.setProperty() in the "postAcquireClientSession" callback - is that the right way to do it? 19:46, 13 October 2011 (UTC)

James - can you please look at this example to see if this is the right approach? If so, I could add it to the wiki page.

public class TenantListener extends SessionEventAdapter implements SessionEventListener {
public static final String TENANT_PROPERTY = "eclipselink.tenant-id";
public void postAcquireClientSession(SessionEvent event) {
	Session session = event.getSession();
	session.setProperty(TENANT_PROPERTY, **value**);

Register this listener in persistence.xml with the property "eclipselink.session-event-listener" and inject the @PersistenceContext as usual.

Does that sound right to you? Thanks! 02:08, 22 December 2011 (UTC)

Back to the top