1 Reply Latest reply on Nov 13, 2008 8:14 AM by Kamil Demecki

    Manually created Hibernate EntityManager vs. injected one

    Alexei Novikov Newbie

      Because of isolated classloading problems with several applications in the same container I have to avoid injecting EntityManager via a @PersistenceContext annotation.

      I tried to use the following code in my stateless bean:

       private EntityManager em;
      
       @PostConstruct
       public void injectEntityManager() {
       EntityManagerFactory emf = Persistence.createEntityManagerFactory("em");
       em = emf.createEntityManager();
       }
      

      It works perfectly. I can see that a JTA type transaction is activated when I request a transaction using @TransactionAttribute and @TransactionManagement annotations. So far so good.

      My question is: do I miss something if I create an EntityManager manually? Are there any gotchas doing it this way? When I try to trace call hierarchies in a debugger, I can see that they are very different, and involve different classes.

      Manual bootstrapping of EntityManager via the Persistence class is only scarcely mentioned in Hibernate and JBoss documentation in context of a Java SE application.

      Can somebody comment on if it is OK to go this way within JBoss container?

      thanks!
      /Alexei

        • 1. Re: Manually created Hibernate EntityManager vs. injected on
          Kamil Demecki Novice

          JBoss uses EnityManager which is involved with TransactioManager and em is proxy so em.find/em.save is thread safe.

          Your code is also thread safe because beans are thread-safe but creating emtnity manager factory has high cost (6 seconds on my machine).

          Persistence.createEntityManagerFactory("em");


          Should be invkoned once.

          If you move creating emf to singleton then there is question if emf.createEntityManager(); has proper transaction if you are using annotations on beans. If you using transactional filter (eg. on web.xml in web apps) which global begin/commit transaction there should be no problem.