我有一个教育小项目。 JPA-Servlet-JSP。现在我要使用PersistanceUnit批注:

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");
    }


但是我尝试emf.createEntityManager();时看到NPE
我的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>


它是一个maven项目,位于src / main / resources / META-INF中(位于j2ee7教程中)。
更新
尝试过:

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




@PersistenceUnit(unitName="AdressBookPU")
private EntityManagerFactory emf;

最佳答案

您正在使用哪个容器?并且您是否在此容器中定义了jta-data-source(jdbc / __ adressbook)?

09-28 13:11