Question

I have a small project for education. JPA-Servlet-JSP. Now I want to use PersistanceUnit annotation:

public class UsersListServlet extends HttpServlet {

    @PersistenceUnit
    private EntityManagerFactory emf;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        EntityManager em = null;
        try {
            em = emf.createEntityManager();

            //query for all the persons in database
            List persons = em.createQuery("select u from Users u").getResultList();
            request.setAttribute("usersList",persons);

            //Forward to the jsp page for rendering
            request.getRequestDispatcher("UsersList.jsp").forward(request, response);
        } catch (Exception ex) {
            throw new ServletException(ex);
        } finally {
            //close the em to release any resources held up by the persistebce provider
            if(em != null) {
                em.close();
            }
        }
        response.setContentType("text/html;charset=UTF-8");
    }

but I see NPE when try emf.createEntityManager(); My persistance.xml:

<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="AdressBookPU">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/__adressbook</jta-data-source>
    <class>com.prokopenko.adressbook.entity.Users</class>
    <class>com.prokopenko.adressbook.entity.MobilePhone</class>
  </persistence-unit>
</persistence>

Its a maven project and persistance.xml located src/main/resources/META-INF (like in j2ee7 tutorial). UPDATE Tried:

@PersistenceContext(unitName = "AdressBookPU")
private EntityManager em;

and

@PersistenceUnit(unitName="AdressBookPU")
private EntityManagerFactory emf;
Was it helpful?

Solution

Which container are you using? And have you defined in this container your jta-data-source(jdbc/__adressbook)?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top