我是JavaEE的新手,目前正在学习JavaEE7。我已经安装并下载了JavaEE7,并下载了NetBeans 8.0.2,因此可以按照允许在此处发布的网络研讨会进行操作:

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

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

在参加网络研讨会大约12分钟之前,我遇到了帖子标题中提到的java.lang.IllegalStateException。演示者在视频中的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)

我广泛搜索StackOverflow和Google,而我不断遇到的答案与persistence.xml文件的位置有关。我正在使用NetBeans,它会自动创建persistence.xml文件并将其放置在Configuration Files文件夹中。

NetBean 8.0.2中的项目布局如下所示:
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在教程中自动生成的Friend.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.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>

}

而且,当然是由NetBean 8.0.2自动生成的看似臭名昭著的persistence.xml文件:
<?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
  • 我已验证我的GlassFish服务器确实具有名为jdbc/sample的资源,该资源已映射到名为SamplePool的池中。我还验证了我的GlassFish服务器具有一个名为SamplePool的连接池。当前将其设置为javax.sql.DataSource资源类型。

  • 我希望对JavaEE有更多经验的人可以指出我在这里缺少的明显之处。也许某些东西已经从JavaEE6更改为JavaEE7,这可能是我出错的原因。

    任何帮助或建议,将不胜感激。

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

    我已经安装了JDK 1.8(更新31),NetBeans 8.0.2和GlassFish 4.1。这个警告是否暗示eclipseLink不适用于JDK 1.8?

    /
    更新#2:好吧,这似乎是一个非常la脚的解决方案。尝试修复了几个小时后。我关闭了GlassFish服务器,从数据库断开连接,执行“清理并构建”,再次启动所有内容,然后重新部署。现在一切似乎都按我的预期进行。我想某处有些不灵通,只有“干净”才能解决问题。啊。
    /

    最佳答案

    显然,我的构建中有些东西有些时髦。我关闭了所有服务器,进行了清理和构建并重新部署。现在,一切似乎都正常了。

    谢谢大家的建议。

    09-10 17:02