users@glassfish.java.net

Re: Persistence in Web Container

From: <glassfish_at_javadesktop.org>
Date: Wed, 10 Oct 2007 10:09:58 PDT

Thank you - the blueprints are very helpful.

I am still encountering a problem, however. The entity manager factory is not being injected via the @PersistenceUnit annotation.&nbsp;&nbsp;Without injection, the code works fine (ie: calling Persistence.createEntityManagerFactory() directly). Am I missing some configuration or dependency?

public class MyFacade implements ServletContextListener {

&nbsp;&nbsp;&nbsp;&nbsp;@PersistenceUnit(unitName = "myPu")
&nbsp;&nbsp;&nbsp;&nbsp;private EntityManagerFactory emf;

&nbsp;&nbsp;&nbsp;&nbsp;public void contextInitialized(ServletContextEvent sce) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ServletContext context = sce.getServletContext();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;context.setAttribute("MyFacade", this);
&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;public void contextDestroyed(ServletContextEvent sce) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (emf.isOpen()) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;emf.close();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;public <T> T find(Class<T> entityClass, Object id) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;EntityManager em = emf.createEntityManager(); /* NullPointerException thrown here */
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;T entity = em.find(entityClass, id);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;em.close();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return entity;
&nbsp;&nbsp;&nbsp;&nbsp;}

}

public class MyServlet extends HttpServlet {

&nbsp;&nbsp;&nbsp;&nbsp;protected MyFacade mf;

&nbsp;&nbsp;&nbsp;&nbsp;public void init(ServletConfig config) throws ServletException {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ServletContext context = config.getServletContext();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mf = (MyFacade) context.getAttribute("MyFacade");
&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;. . .
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MyEntity myEntity = mf.find(MyEntity.class, id);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;. . .
&nbsp;&nbsp;&nbsp;&nbsp;}

}
[Message sent by forum member 'shelleyb' (shelleyb)]

http://forums.java.net/jive/thread.jspa?messageID=239352