Reputation: 71
I'm new to JavaEE and currently learning JavaEE7. I have JavaEE7 installed and downloaded NetBeans 8.0.2 so I could follow allow with the Webinar published here:
https://www.youtube.com/watch?v=sCNslREYpD0&spfreload=10
This tutorial in the video uses JavaEE6 rather than JavaEE7.
I made it about 12 minutes into the Webinar before I encountered the java.lang.IllegalStateException
mentioned in the title of my post. At 12:18 in the video, the presenter adds a @PersistenceUnit
to the code, and then an EntityManagerFactory
. Even though I have followed his tutorial very carefully, I'm having issues with persistence and keep getting the following Exception:
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)
I have search StackOverflow and Google extensively, and the answer I keep coming across relates to the location of the persistence.xml
file. I'm using NetBeans which automatically creates and places the persistence.xml
file in a Configuration Files
folder.
The project layout in NetBean 8.0.2 looks like the following:
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
Here is Friend.java
file that was automatically generated by NetBeans as part of the tutorial:
/*
* 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 + " ]";
}
}
Here is the TestServlet.java
file:
/*
* 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>
}
And, of course, the seemingly infamous persistence.xml
file that was automatically generated by NetBean 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>
I tried a variety of things like:
injecting a PersistenceContext
instead of a PersistenceUnit
and getting an EntityManager
directly from there instead of using an EntityManagerFactor
(not sure if I did that correctly).
modifying my @PersistenceUnit
to @PersistenceUnit(unitName="JavaEE7WebinarPU")
. This didn't help much. It just changed my error from:
java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName null
to
java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName JavaEE7WebinarPU
jdbc/sample
which is mapped to a pool named SamplePool
. I also verified that my GlassFish server has a Connection pool named SamplePool
. It is currently set as a javax.sql.DataSource
resource type.I was hoping someone with some more experience with JavaEE might be able to point out something obvious that I'm missing here. Or maybe something that has changed from JavaEE6 to JavaEE7 which may be the cause of my error.
Any help or suggestions would be greatly appreciated.
/
UPDATE: I just ran a Clean and Build
in NetBeans and saw the following warning:
/
warning: Supported source version 'RELEASE_6' from annotation processor 'org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor' less than -source '1.8'`
I have JDK 1.8 installed (update 31), NetBeans 8.0.2, and GlassFish 4.1. Is this warning suggesting that eclipseLink won't work with JDK 1.8?
/ UPDATE #2: Ok, well this seems to be a very lame resolution. After trying to fix this for a couple of hours. I shut down my GlassFish server, Disconnected from my database, performed a 'Clean and Build', started everything back up again, and redeployed. Now everything seems to be working as I expect it to. I suppose something got a little wonky somewhere and only a 'clean' was able to resolve the issue. Ugh. /
Upvotes: 3
Views: 5539
Reputation: 95
No problem buddy its very easy just add this in persistence.xml file
<?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>
You have an option at persistence class generated by netbeans to name your persistence unit. After naming it just do a clean and build and you will get your answer.
Upvotes: 0
Reputation: 2333
James, I think it is a simple solution. change from
@PersistenceUnit
to
@PersistenceUnit(unitName="JavaEE7WebinarPU")
also see https://docs.oracle.com/javaee/6/api/javax/persistence/PersistenceUnit.html
Upvotes: 0
Reputation: 71
Apparently something in my build got a little funky. I shut down all my servers, did a Clean and Build and redeployed. Now, everything seems to be working.
Thanks all for your suggestions.
Upvotes: 1
Reputation: 79
You have specified entity manager in your post and you trying to access entity manager both are different please see You should do like this
@PersistenceContext(name="entiyManager")
EntityManager entitymanager;
Also you need to initialized your entitymanager factory
Upvotes: 0
Reputation: 2288
What I found missing in your persistence.xml is the provider. In your persistence-unit element add the following tag also
<provider> provider_name</provider>
check which provider you are using
Upvotes: 0