1 Reply Latest reply on Aug 14, 2013 5:15 PM by james_sutherland

    Multitenancy and Entity Manager


      We are using JPA with eclipse link. We have extensive JPA queries. Our code is in production for a while. Now we have  a business use case, to support multitenancy.

      We will be using the Oracle Pluggable Database mechanism where each client will have their database.

      In our code, in order to create an EntityManager, we have defined a Singleton Class.

      In places where we do any JPA queries, we fetch the EntityManager object from this Singleton Class and store the instance of EntityManager as a static variable and reuse in our code.


      In multitenant use case, will the EntityManager instance be specific to the database of each of the client?

      My doubt is do we need to change our model of preparing the EntityManager and  instantiate the EntityManager at class level or the current model works without any issues?

        • 1. Re: Multitenancy and Entity Manager

          An EntityManager is meant to be a short lived object, either per request, per transaction, or per user session at most.  You should not be storing an EntityManager in a static variable and sharing among multiple users or threads.


          You should have a single EntityManagerFactory, but create an EntityManager per request.


          For multitenancy, if you have multiple databases, then you will want to create a new EntityManagerFactory per tenant, using the Persistence.createEntityManagerFactory() API, and pass a Map of properties including the tenant's database url.