gpt4 book ai didi

java - PersistanceUnit 注解不注入(inject)

转载 作者:行者123 更新时间:2023-11-29 08:49:25 25 4
gpt4 key购买 nike

我有一个小的教育项目。 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 的 persistance.xml(就像在 j2ee7 教程中一样)。更新尝试过:

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

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

最佳答案

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

关于java - PersistanceUnit 注解不注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23496116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com