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?

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.

Similar Messages

  • JPA and Entity manager.

    Hi all,
    I have a "simple" question:
    Should I create a class to manage entity manager and entity manager factory on JPA2?
    Why do I ask that? Because I read on J2EE tutorial:
    With a container-managed entity manager, an EntityManager instance’s persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction.
    To obtain an EntityManager instance, inject the entity manager into the application component:
    @PersistenceContext
    EntityManager em;
    I'm using JSF2, JPA2, JTA and Glassfish3.1 on the NetBeans 7.0.1.
    The wizard that creates the JSF's pages from entity class does a good work but I have some problem in the other classes.
    When I call EntityManager it returns null!
    The strange thing is that it works properly the first time, when I recall the EntityManager from another xhtml page and from another class the entity manager returns NULL!
    So I would understand if the creation of a class for manage the EntityManagerFactory and EntityManager could help me.
    Thank you for your future help!

    Filippo Tenaglia wrote:
    Hi all,
    I have a "simple" question:
    Should I create a class to manage entity manager and entity manager factory on JPA2?That question is far from complete, as the answer to this one is "depends on what you want to do!"
    Why do I ask that? Because I read on J2EE tutorial:
    With a container-managed entity manager, an EntityManager instance’s persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction.
    To obtain an EntityManager instance, inject the entity manager into the application component:
    @PersistenceContext
    EntityManager em;
    Given this information...
    I'm using JSF2, JPA2, JTA and Glassfish3.1 on the NetBeans 7.0.1.That answer to your question is "NO", because you have a container available to you that can do the work (Glassfish). It makes no sense using Glassfish and then purposely ignoring the features it has to offer.
    Lets get back to basics: you are doing something wrong here. You have to figure out what, you can only do that if you keep studying and getting a more complete understanding. If you are having trouble realizing that, perhaps you should start over without the help of any wizard at all; wizards are only useful when you are already experienced, right now the fact that code is generated is hindering you a lot because you will have a strong impulse to believe there can be no mistake; unfortunately there is no such safety net. The fact that you used the word "weird" is enough proof of this by the way. There is nothing weird here, just a mistake being made that has to be corrected.
    And for the future: what IDE (Netbeans in your case) you use to develop really makes absolutely no difference at all. What is more interesting is which version of Java your are using, which can likely be Java 6 or Java 7 nowadays.

  • How to use application managed entity manager in EJB?

    I finish reading The EntityManager Interface in JEE tutorial.
    I know I can use container manager entity manager in EJB, but I want to explore how to use application managed entity manager in EJB.
    Can I use application managed entity manager in EJB (container management JTA transaction is used)? Where do I should close entity manager if can?
    The following is an example from JEE tutorial, but didn't find where to calose entity manager. and can I create mutiple EntityManagerFactory objects and Entity Manager objects to use them in a JTA transaction?
    @PersistenceUnit
    EntityManagerFactory emf;
    EntityManager em;
    @Resource
    UserTransaction utx;
    em = emf.createEntityManager();
    try {
      utx.begin();
      em.persist(SomeEntity);
      em.merge(AnotherEntity);
      em.remove(ThirdEntity);
      utx.commit();
    } catch (Exception e) {
      utx.rollback();

    Seems like a very poor example, the whole power of EJBs is to use Container Managed Transactions so you don't NEED to manage the transaction and the entity manager yourself. What you posted is code I would expect in a non-JEE application, or in a piece of code which requires fine-tuned transaction boundaries such as batched data importing logic.
    If I were you I'd research JPA in steps.
    a) learn about JPA as an API outside of the scope of EJBs (recommended reading: the book 'Pro JPA 2')
    b) learn about Container Managed Transactions in EJBs
    c) learn about Bean Managed Transactions in EJBs
    Right now you're rushing into c). I can understand that it raises many question marks at this point.

  • How to inherit one enity method and to create entity manager factory

    Hi All,
    i have totally 5 databases where one database has the connection details of all other 4 databases.i am using EJB 3.0 and using MVC architecture.is there any possibility to get the details in that datbase and create entity manager factory based on that detail.i defined all the database connection in persistence.xml.

    Hi,
    is there any oher possibility to create entity manager factory dynamically?

  • Problem with non-container managed entity manager

    i am working on a project, in which i am using entity beans.i use netbeans, glassfish as application server and toplink as persistence provider .
    i created a java class that handles all the operations with the entitys, which means i using non-container managed entity manager.
    in the constructor
    try{
                EntityManagerFactory emf = Persistence.createEntityManagerFactory("voidPU");
                entityManager = emf.createEntityManager();
            catch(Exception ex){
                throw new EJBException(ex.getMessage());
            }then i call a function in this class from a servlet
    the code of the function
    List users = null;
            try {
                ProgLanguages progLanguage = entityManager.find(ProgLanguages.class, languageId);
                users = (List) progLanguage.getUserIdCollection();
            catch(IllegalStateException illegalStateException){
                throw new EJBException(illegalStateException.getMessage());
            catch(IllegalArgumentException illegalArgumentException) {
                throw new EJBException(illegalArgumentException.getMessage());
            }i got an IllegalArgumentException saying Unknown entity bean class: class vanguard.server.entity.ProgLanguages, please verify that this class has been marked with the @Entity annotation
    what confuses me is that sometimes it works and most of the time it does not work, have i made anything wrong?, or there is a problem with any of the tools netbeans, glassfish, or toplink?

    Is it always the same entity that is reported as 'unknown' ? You mention that it works sometimes but is it the same deployment and the same code that works? The first thing I would verify is that the ear is being created as expected by netbeans. Check the persistence.xml file and verify that all of the classes are listed that will be used as entities.
    --Gordon                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Topic: How to obtain entity manager in application server?

    Hey,
    How to obtain Entity manger in application server ?
    The class is a simple class (no Ejb), and i can call to this class from Ejb or from inner schdeuler process (not container management)
    I want that if i call to this calss from Ejb , that the entity manager transaction will join to the global transaction.
    Thank you

    Hi,
    entity managers outside EJBs can be created using a javax.persistence.EntityManagerFactory.
    Regards

  • Does refreshing a report that includes Scope and Entity require elevated rights / permissions?

    This relates to the following thread:
    Why does refreshing a report in the EPM Add-In need to edit the Ownership Manager?
    Since I've received no responses on the above thread, I thought I might approach this from a different angle.
    If we have a report that includes both Scope and Entity, in SAP BPC 10 NW (801 SP03) / EPM Add-In 10.0 SP 16 Patch 1, does this require a user to have elevated permissions in order to refresh the report?  I ask because I have users who have rights to view reports, but they error out when they try to refresh a report's data, only where Scope and Entity are used in the report.  The tasks that error are:
    P0081
    Run Consolidation Tasks
    P0082
    View Ownership Manager
    P0083
    Edit Ownership Manager
    I do not understand why any of these should even be called by refreshing the report, as the user is simply "viewing" data that already exists in the environment.
    Can someone please shed some light on this or point me in the direction of how I can go about resolving this issue?
    Your help is greatly appreciated.
    Jeff

    Hi
    I am facing the same issue despiste the elevated app permission as per
    https://msdn.microsoft.com/en-us/library/office/jj822159.aspx?f=255&MSPPError=-2147217396
    I still had the error 401
    the solution for me was
    Under list settings -> advanced settings update the Create and Edit access settings from "Create and edit all items"
    the add the user the right to add only ( no edit , no delete) .
    Eric Caron

  • Entity manager Slow down

    Hey all Well I was just wonder if you guys could give me some insight? I am using the entity manager and It seems like I can do a transaction.. But as I keep doing the transaction to add elements.. It runs fine but then all of a sudden it just hangs? here my code? any insight would be greatly appreciated.. even if its just a theory
    selectedCustomer.getLevelIdSellCollection().add(item);               
    EntityTransaction tx = getEntityManager().getTransaction();
                    tx.begin();
                    getEntityManager().merge(Customer);
                    tx.commit();
                    getEntityManager().refresh(Customer);
                                   Message was edited by:
    jbayuga
    Message was edited by:
    jbayuga

    Welcome to the forum.
    If you have created either a Roll, or Crawl, with the Animation Preset, then you will want to increase the Duration of that Title, to slow it down. You can do this by click+dragging on the Tail of the Title.
    Or, you can create a static Title, then animate it by Keyframing the Fixed Effect>Motion>Position over time. That allows for much more control.
    Good luck,
    Hunt

  • Entity Manager in EJB3

    Could someone explain the concept of
    1. Entity manager.
    2. Types and Purpose of Entity manager
    3. How they are injected
    Thanks in advance.

    A start to covering these questions here:
    http://en.wikibooks.org/wiki/Java_Persistence/Runtime
    For the meaning of life go here:
    http://en.wikipedia.org/wiki/Meaning_of_life
    -- James : http://www.eclipselink.org

  • Recommended way of getting entity manager from pojo class

    Hi,
    In our application we have the need or retrieving entity manager from 'pojo' classes.
    More specifically we have singleton classes which act as 'data' repositories and are accessed from both servlets and ejb.
    I'm aware that the repositories classes might be problematic, but in the current stage we can't perform significant change in application structure so I am looking for a 'fast' solution as possible.
    The best way will be to lookup entityt manager in JNDI, but as I undestand this feature is not avaialabe in weblogic.
    I understand that the preffered way for getting entity manager in such situation is by using @PersistenceUnit annotion on the calling location and lookup entityManager by that name in the pojo. This is however problematic for us since since we access the repositories from variouse locations (many different classes).
    Possible additional solutions we thought of:
    - creating an 'entity manager factory' locator ejb. This is an ejb with no transaction attribute, which has one method getEntityManagerFactory. It injects entityManagerFactory and returns it. This is the fastest soltion to implement. Is this a valid one?
    - using application managed entity manager in such situations. We have a problem doing so now because the creation seems to fail for variouse reasons.
    What is the recommended way?
    Thanks.

    To obtain an EntityManager instance, first must obtain an EntityManagerFactory instance by injecting it into the application component by means of the javax.persistence.PersistenceUnit annotation:
    @PersistenceUnit
    EntityManagerFactory emf;
    Then, obtain an EntityManager from the EntityManagerFactory instance:
    EntityManager em = emf.createEntityManager();
    http://download.oracle.com/javaee/5/tutorial/doc/bnbqw.html
    Edited by: dvohra16 on Apr 14, 2011 5:06 PM

  • Database Entity Manager Concept

    Hello Forte-Users,
    currently I work with the Concept of the White-Paper:
    Forte Database Integration Patterns
    Forte Consulting
    May 1996
    to integrate Database-Access into my Warehouse-Application.
    Because the hole Application is delivered step by step and we are new
    in using Forte, I use for the first step only the patterns described for
    the DBEntityMgr to get a "feeling".
    The problem is, that if I use the DBEntityMgr-Concept and have many
    BaseClasses to access I have a lot of interface-calls like
    GetCustomer,GetProducts,etc..
    The Database Session Router will also not solve this "problem" in future,
    because the
    ApplicationEntityMgr has than the same problem.
    Question: Know anyone a way, based on the upon described facilities to use
    this strategy with a solution to make more "EntityMgrSO's" to get a smaller
    DBEntityMgr-Interface?
    The Database Session Router is planed for using when the Application should
    be used from more Users and when running the SO's on a WorkGroup-Server.
    Question: Know anyone a way there to split the ApplicationEntityMgr?
    Every reply is welcome.
    Thanks forward to all
    Joseph Mirwald
    Bachmeier & Sporrer
    GERMANY
    EMAIL: [email protected]
    Don't worry, which bug you wanna have today?

    ...snip
    >> The bad part is that now, the "client" of the entity manager
    must know
    >> which entity manger to call for any particular set of
    data. This negates
    >> a significant part of the advantage of using the single
    interface into the
    >> persistence layer.
    snip ...
    [KUBASADA Manjunatha] We can avoid this problem by having the
    EntityMgrSO method determine which entity manager to use. The client can
    pass a parameter indicating which object to get. The client call would
    look like,
    myobject = EntityMgrSO.GetEntity(myobjectindicator);
    OR
    EnitytMgrSO.GetEntity(output myobj : object);
    In the second case, the GetEntity method uses the run time type
    of myobj to determine which entity manager to call. In both cases the
    EntityMgrSO returns an object of type Object; the client would have to
    cast it to the appropriate type.
    Don, are there any downsides to this approach ?
    Manjunatha Kubasada
    Complete Business Solutions Inc.
    email : [email protected]
    Ph : (248) 488-2088 X 3480
    -----Original Message-----
    From: Don Nelson [SMTP:[email protected]]
    Sent: Saturday, November 29, 1997 4:05 PM
    To: Joseph Mirwald
    Cc: forte-users
    Subject: Re: Database Entity Manager Concept
    Joeseph,
    The concept of the entity manager having less interfaces is both good
    and
    bad. The good part is mostly related to development - splitting up
    the
    calls to the various SQL managers among several entity managers allows
    more
    flexibility in terms of which classes have to be checked out of the
    repository to add to or update the interfaces.
    >> The bad part is that now, the "client" of the entity manager
    must know
    >> which entity manger to call for any particular set of
    data. This negates
    >> a significant part of the advantage of using the single
    interface into the
    >> persistence layer.
    I've used both strategies in the past, and I tend to stay with one
    entity
    manager with a large number of interfaces. It moves the
    responsibility of
    knowing where to get the data from the client to the service, where it
    usually belongs. The only real time penalty is when you compile the
    partition - there will be more to compile. But since they are just
    interafaces, it shouldn't be that big of a deal.
    Don
    At 10:49 AM 11/28/97 -0500, Joseph Mirwald wrote:
    Hello Forte-Users,
    currently I work with the Concept of the White-Paper:
    Forte Database Integration Patterns
    Forte Consulting
    May 1996
    to integrate Database-Access into my Warehouse-Application.
    Because the hole Application is delivered step by step and we are new
    in using Forte, I use for the first step only the patterns describedfor
    the DBEntityMgr to get a "feeling".
    The problem is, that if I use the DBEntityMgr-Concept and have many
    BaseClasses to access I have a lot of interface-calls like
    GetCustomer,GetProducts,etc..
    The Database Session Router will also not solve this "problem" infuture,
    because the
    ApplicationEntityMgr has than the same problem.
    Question: Know anyone a way, based on the upon described facilitiesto use
    this strategy with a solution to make more "EntityMgrSO's" to get asmaller
    DBEntityMgr-Interface?
    The Database Session Router is planed for using when the Applicationshould
    be used from more Users and when running the SO's on aWorkGroup-Server.
    Question: Know anyone a way there to split the ApplicationEntityMgr?
    Every reply is welcome.
    Thanks forward to all
    Joseph Mirwald
    Bachmeier & Sporrer
    GERMANY
    EMAIL: [email protected]
    Don't worry, which bug you wanna have today?
    ============================================
    Don Nelson
    Regional Consulting Manager - Rocky Mountain Region
    Forte Software, Inc.
    Denver, CO
    Corporate voice mail: 510-986-3810
    aka: [email protected]
    ============================================
    "The good thing about drawing a tiger is that it automatically makes
    your
    picture fine art." - Hobbes

  • Transactions, Persistence Contexts and Entity Managers... Oh My!

    Hi
    I am just getting into J2EE and EJB3. I have no prior experience with EJB2, we avoided it with our own POJO data access framework. With the advent of EJB3 we would like to use it in a new application.
    I am reading the book "Pro EJB 3" by Ketih and Schincariol and am having trouble wrapping my head around then Entity Manager chapter. I don't think it's any fault of the authors, but somehow it's just not coming together in my head. Perhaps it's because I have no real prior EJB experience.
    Can anyone point me to a resource that gives an overview of the relationships between Transactions, Persistence Contexts and Entity Managers? Or perhaps I just have to keep mulling it over until it all comes together...?
    Thanks in advance!

    Hi Shelli,
    I haven't read that book but I don't know of a good writeup of the tx topic specifically outside
    of the spec itself. There are certainly a lot of combinations, between container-managed
    vs. bean-managed EntityManagers, and JTA vs. resource-local. However, the
    common usage case within Java EE -- container-managed and JTA -- is very simple.
    In this case, the container automatically associates the persistence context with the
    active global transaction. If you make a call to another Java EE component within the
    same transaction and that component accesses a container-managed EntityManager
    for the same persistence unit, the persistence context is automatically propagated so
    that both components "see" the same persistence context.
    --ken                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • A question about entity manager in stateless session bean.

    JSR 220 ejbcore, page 47 : stateless session bean: All business object references of the same interface type for the same stateless session bean have the "same object identity", which is assigned by the container.
    So, if we have two session beans in client code...
    @EJB Cart cart1;
    @EJB Cart cart2;
    then cart1.equals(cart2)==true
    If we declare entity manager in stateless session bean:
    @PersistenceContext( unitName="ds" ,type=PersistenceContextType.TRANSACTION)
    private EntityManager em;If cart1 and cart2 are the same reference, do we have any problem when using the same reference(maybe the same em? ) to get data from db?

    If cart1 and cart2 are the same reference, do we have
    any problem when using the same reference(maybe the
    same em? ) to get data from db?No. In EJB, there is a distinction between the EJB reference and the bean instance.
    Each time you make an invocation on an EJB reference for a stateless session bean,
    the container can choose any instance of that bean's bean class to process the
    invocation. That's true whether you invoke the same reference multiple times or
    two difference references to the same bean.
    Each bean instance is guaranteed to be single-threaded.

  • How many ejbCreate() can be in Session and Entity Bean???

    Hi,
    How many ejbCreate() method can be in a Session and Entity
    Bean???
    How many can be in Stateless and Stateful SessionBean???
    How many can be in CMP and BMP SessionBean???
    Thanks,
    JavaCrazyLover

    How many ejbCreate() method can be in a Session
    ion and Entity
    Bean???For Stateful Session Beans and Entity Beans, as many as you'd like.
    Stateless Session beans can only have one, since their ejbCreate methods can not take any parameters.
    >
    >
    How many can be in CMP and BMP SessionBean???If you mean CMT/BMT(Container-Managed transactions / Bean-Managed Transactions), then
    the answer is the same. The create method requirements are independent of the transactional nature of the bean.
    If you really mean CMP/BMP(Container-Managed Persistence / Bean-Managed Persistence) , it doesn't apply to session beans, only entity beans. However, even for entity beans, CMP vs. BMP has no bearing on the rules regarding # of create methods.
    --ken
    >
    >
    Thanks,
    JavaCrazyLover

  • Cfdiv and session managment

    I am working on a website that uses session managment for
    security login.
    The site was developed with CF6, and we are now trying
    migrating it to CF8.
    Currently, forms are submitted passing the session token in
    the URL like this:
    <form
    action="Assignments.cfm?<cfoutput>#session.URLToken#</cfoutput>"
    method="post">
    </form>
    I'm trying to integrate CFDIV into the code, so I have
    <cfform>
    </cfform>
    <CFDIV bind="url:AnotherForm.cfm ...>
    When I run this, Instead of including "AnotherForm.cfm" the
    session is not getting passed and the system logs me out.
    I've tried
    bind="url:AnotherForm.cfm?<cfoutput>#session.URLToken#</cfoutput>
    (also logs me out)
    and putting the code in a
    <cfdiv>
    <cfform
    action="AnotherForm.cfm?<cfoutput>#session.URLToken#</cfoutput>">
    </cfform>
    <cfdiv>
    Doesn't abend, but doesn't do anything either.
    So, does anybody know how to incorporate cfdiv into session
    management?
    thank you,
    Steve Shapiro
    University of Oregon

    Yes, entity managers are allowed to have one transaction active at any given time.
    Assuming that you have a resource-local entity manager (from your comment about JDBC and non-JTA data sources) then any container-managed transaction associated with a session bean is going to be a JTA transaction and be completely independent of the entity manager transaction (as long as the non-JTA-data source is properly set to a data source that is not a JTA data source).
    If you are using a non-JTA data source element to configure your database then the entity manager will simply do a getConnection() on the data source. If you are using the JDBC persistence properties in persistence.xml then the connection will be obtained directly from the JDBC driver.

Maybe you are looking for

  • Download Window Does Not Close Upon Completion of Download

    I download a file, the Download Window opens, and asks where I want the file (I set that Tool-Option), but when it is done, the window does not close, even though the Option is set telling it to close when the download is complete == This happened ==

  • MacBook Pro HD issues; won't boot to any drive; need to recover data

    *Apologies in advance for the lengthy post. I just want to be sure I include as much detail as possible. Thanks in advance for reading all of this and offering any thoughts and suggestions. I have a 13-inch late 2011 MacBook Pro running OS 10.7. The

  • What happened to ACR

    When running the latest version of Lightroom (I reinstalled it today) and I use the "edit in Photoshop" command on a DNG file they are opening directly in Photoshop, bypassing ACR.  Yesterday they went to ACR first.  I've reinstalled Lightroom and Ph

  • Why do my buttons disappear in Firefox?

    http://www.mayakaimal.com/recipes/madras-chicken-biriyani#.UWMvexm6__t They show up everywhere else...

  • Output Blank

    Please help me . I've the problem as following : DEFINE GLOBAL: CONN_TEXT @TEXT1 @TEXT2 CONN_TEXT is a field on the template TEXT1 and TEXT2 are the global fields in the Datastream. It works perfect, if the fields TEXT1 and TEXT2 exist in the datastr