1 Reply Latest reply on Aug 24, 2012 2:57 AM by Wolf-Dieter Fink

    Injection of EntityManager using @PersistenceContext fails in EJB tier

    Raffael Bechara Rameh Newbie

      Hi there,

       

      I have the following EJB, that works fine:

      (the code below has been simplified)

       

      @Stateless

      public class LoginSession implements LoginSessionLocal {

       

          @PersistenceContext

          private EntityManager em;

       

          public void saveUser(User user) throws FacadeException {    

                em.persist(user);

          }

      }

       

       

      But I want to change it a little bit, dividing it in two classes, moving the blue lines from the Session class to the DAO implementation, like the following:

       

      @Stateless

      public class LoginSession implements LoginSessionLocal {

       

          public void saveUser(User user) throws FacadeException {    

                (new LoginDAO()).saveUser(user);

          }

      }

      ------------------------------------------------------------------

      public class LoginDAO  {

       

          @PersistenceContext

          private EntityManager em;

       

          public void saveUser(User user) {    

                em.persist(user);

          }

      }

       

      Unfortunatelly, the injection does not work in the second case. The variable "em" is null. It works only in the first case. The annotation @PersistenceContext doesn't work if I put it in the utility class LoginDAO. It only works if I put it in the EJB implementation LoginSession.

       

      Why? How can we solve this problem? Is it a bug of JBoss 7.1?

       

      I am using JBoss 7.1 Community and JDK 1.7. It's an EJB Eclipse project within a EAR.

       

      Can someone help me?

       

      Thanks in advance,

      Raffael Bechara