PersistanceUnit注释不会注入

时间:2014-05-06 13:29:40

标签: java jpa

我有一个小型的教育项目。 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项目,persistance.xml位于src / main / resources / META-INF(就像在j2ee7教程中)。 UPDATE 尝试:

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

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

1 个答案:

答案 0 :(得分:0)

您使用的是哪个容器?你有没有在这个容器中定义你的jta-data-source(jdbc / __ adressbook)?