1 Reply Latest reply on Feb 21, 2008 5:16 PM by 843833

    getting an EntityManager inside a JavaBean

      Hi all,

      I'm new to the whole JavaBean/Hibernate persistence framework. Before I started using hibernate, I wrote a database class which created preparedstatements and returned results as a collection. I want to learn hibernate and have gotten it working, but am having issues doing some more advanced things. I created a namedquery that selects a session by the sessionId which is generated from the servlet container. I want to use this named query and to do that I do the following:
      log.debug("initializing session");
           EntityManagerFactory emf = Persistence.createEntityManagerFactory("defaultStorage");
           EntityManager em = emf.createEntityManager(); // Retrieve an application managed entity manager
           org.hibernate.Session session = hibernateStorage.getSessionFactory().getCurrentSession();
           Query query = em.createNamedQuery("Session.findBySessionId");
           query.setParameter("sessionId", sessionId);
           Session loadedSession = (Session) query.getSingleResult();
      The code I was trying to use before was supposed to inject the entityManager inside it. I tried using that but got a nullPointerException cause it apparently hadn't been initialized. I read somewhere that it won't be initialized until after the constructor for the bean is called, so I made a separate function that is called after construction and still no go.
      @PersistenceContext(unitName = "persistenceUnit")
      private EntityManager em;
      So, my question is:

      How can I get an EntityManager in order to get access to a namedQuery in my code?

        • 1. Re: getting an EntityManager inside a JavaBean
          I actually figured it out on my own. In order to have the EntityManager injected, I have to be using the proper EJB 3.0 container. In addition, it appeared that the underlying error was not having the hibernate structure setup properly. So, I am just using the J2SE method of getting the EntityManager (through an EntityManagerFactory).