1 Reply Latest reply: May 9, 2014 3:26 AM by gimbal2 RSS

    How to use application managed entity manager in EJB?

    Scofield Wang

      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();

      }

        • 1. Re: How to use application managed entity manager in EJB?
          gimbal2

          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.