java.lang.IllegalStateException:无法为unitName null检索EntityManagerFactory

时间:2015-01-23 05:55:20

标签: java java-ee jpa netbeans glassfish

我是JavaEE的新手,目前正在学习JavaEE7。我安装了JavaEE7并下载了NetBeans 8.0.2,因此我可以通过此处发布的网络研讨会来关注:

https://www.youtube.com/watch?v=sCNslREYpD0&spfreload=10

视频中的本教程使用JavaEE6而不是JavaEE7。

在我遇到帖子标题中提到的java.lang.IllegalStateException之前,我在网络研讨会上花了大约12分钟。在视频的12:18处,演示者会在代码中添加@PersistenceUnit,然后在EntityManagerFactory中添加java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName null at com.sun.enterprise.container.common.impl.EntityManagerFactoryWrapper.getDelegate(EntityManagerFactoryWrapper.java:103) at com.sun.enterprise.container.common.impl.EntityManagerFactoryWrapper.createEntityManager(EntityManagerFactoryWrapper.java:114) at org.glasssfish.samples.TestServlet.processRequest(TestServlet.java:79) at org.glasssfish.samples.TestServlet.doGet(TestServlet.java:103) at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282) at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167) at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201) at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175) at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235) at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201) at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133) at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112) at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77) at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561) at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545) at java.lang.Thread.run(Thread.java:745) 。虽然我非常仔细地阅读了他的教程,但我遇到了持久性问题,并且一直遇到以下异常:

persistence.xml

我广泛搜索StackOverflow和Google,我不断遇到的答案与persistence.xml文件的位置有关。我使用NetBeans自动创建并将Configuration Files文件放在Web Pages WEB-INF index.html Source Packages org.glassfish.samples TestServlet.java org.glassfish.samples.model Friend.java Libraries JDK 1.8 (Default) GlassFish Server 4.1 Configuration Files MANIFEST.MF persistence.xml 文件夹中。

NetBeans 8.0.2中的项目布局如下所示:

Friend.java

以下是NetBeans作为教程的一部分自动生成的/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.glasssfish.samples.model; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author james */ @Entity @Table(name = "FRIEND") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Friend.findAll", query = "SELECT f FROM Friend f"), @NamedQuery(name = "Friend.findByName", query = "SELECT f FROM Friend f WHERE f.name = :name"), @NamedQuery(name = "Friend.findByAge", query = "SELECT f FROM Friend f WHERE f.age = :age")}) public class Friend implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Size(min = 1, max = 30) @Column(name = "NAME") private String name; @Column(name = "AGE") private Integer age; public Friend() { } public Friend(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public int hashCode() { int hash = 0; hash += (name != null ? name.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Friend)) { return false; } Friend other = (Friend) object; if ((this.name == null && other.name != null) || (this.name != null && !this.name.equals(other.name))) { return false; } return true; } @Override public String toString() { return "org.glasssfish.samples.model.Friend[ name=" + name + " ]"; } } 文件:

TestServlet.java

以下是/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.glasssfish.samples; import java.io.IOException; import java.io.PrintWriter; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceUnit; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.glasssfish.samples.model.Friend; /** * * @author james */ @WebServlet(name = "TestServlet", urlPatterns = {"/TestServlet"}) public class TestServlet extends HttpServlet { @PersistenceUnit EntityManagerFactory emf; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet TestServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>"); // int count; if (request.getSession().getAttribute("count") == null) { count = 0; } else { count = (Integer)request.getSession().getAttribute("count"); } request.getSession().setAttribute("count", ++count); out.println("Accessed again: " + request.getSession().getAttribute("count")); Friend f = (Friend)emf.createEntityManager().createNamedQuery("Friend.findAll").getResultList().get(0); out.println("Friend name: " + f.getName()); out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> } 文件:

persistence.xml

当然,NetBeans 8.0.2自动生成的看似臭名昭着的<?xml version="1.0" encoding="UTF-8"?> <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="JavaEE7WebinarPU" transaction-type="JTA"> <jta-data-source>jdbc/sample</jta-data-source> <exclude-unlisted-classes>false</exclude-unlisted-classes> <properties/> </persistence-unit> </persistence> 文件:

PersistenceContext

我尝试过各种各样的事情:

  • 注入PersistenceUnit代替EntityManager并直接从那里获取EntityManagerFactor而不是使用@PersistenceUnit(不确定我是否正确执行了此操作)

  • @PersistenceUnit(unitName="JavaEE7WebinarPU")修改为java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName null。这并没有多大帮助。它只是改变了我的错误:

java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName JavaEE7WebinarPU

jdbc/sample

  • 我确认我的GlassFish服务器确实有一个名为SamplePool的资源,该资源映射到名为SamplePool的池。我还验证了我的GlassFish服务器有一个名为javax.sql.DataSource的连接池。它目前设置为Clean and Build资源类型。

我希望有更多JavaEE经验的人可以指出我在这里遗漏的明显事实。或者也许是从JavaEE6变为JavaEE7的东西,这可能是我的错误的原因。

非常感谢任何帮助或建议。

/ 更新:我刚刚在NetBeans中运行warning: Supported source version 'RELEASE_6' from annotation processor 'org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor' less than -source '1.8'` 并看到以下警告: /

{{1}}

我安装了JDK 1.8(更新31),NetBeans 8.0.2和GlassFish 4.1。这个警告是否表明eclipseLink不能使用JDK 1.8?

/ UPDATE#2:好吧,这似乎是一个非常蹩脚的决议。在尝试解决这个问题几个小时之后。我关闭了我的GlassFish服务器,断开了与数据库的连接,执行了“清理和构建”,重新启动了所有内容并重新部署。现在一切似乎都在按照我的预期发挥作用。我想某些东西在某个地方有点不稳定,而且只有一个干净的&#39;能够解决这个问题。啊。 /

5 个答案:

答案 0 :(得分:1)

显然我构建的东西有点时髦。我关闭了所有服务器,执行了清理和构建并重新部署。现在,一切似乎都在起作用。

感谢大家的建议。

答案 1 :(得分:0)

我在persistence.xml中发现缺少的是提供程序。在persistence-unit元素中,还添加以下标记

<provider> provider_name</provider>

检查您正在使用的提供商

答案 2 :(得分:0)

您已在帖子中指定了实体管理员,并且您尝试访问实体管理器两者都不同请参阅 你应该这样做

 @PersistenceContext(name="entiyManager")
 EntityManager entitymanager;

您还需要初始化您的实体管理工厂

答案 3 :(得分:0)

詹姆斯,我认为这是一个简单的解决方案。 改变

@PersistenceUnit

@PersistenceUnit(unitName="JavaEE7WebinarPU")

另见https://docs.oracle.com/javaee/6/api/javax/persistence/PersistenceUnit.html

答案 4 :(得分:0)

没问题哥们很容易在persistence.xml文件中添加它

    <?xml version="1.0" encoding="UTF-8"?>

    <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
 <persistence-unit name="JavaEE7WebinarPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/sample</jta-data-source>
  <properties>
  <property name="eclipselink.ddl-generation" value="create-tables"/>
  </properties>
</persistence-unit>
</persistence>

您可以选择netbeans生成的持久性类来命名持久性单元。在命名后,只需做一个干净的构建,你就会得到答案。