NameNotFoundException in Container Managed EntityManager - jpa

I am trying to use Container Managed EntityManager, however I am getting NameNotFoundException. I have tried adding entries in web.xml but in vain.
#Stateless
#Path("/mypath")
public class EmployeeService {
#EJB
private EmployeeDAO employeeDAO;
#GET
#Path("/myresults")
#Produces(MediaType.APPLICATION_JSON)
public Employee getValues() {
Employee emp = new Employee();
try {
emp = employeeDAO.getEmployees(); // exception here
} catch (Exception ex) {
ex.printStackTrace();
}
return emp;
}
EmployeeDAO code snippet
public class EmployeeDAO {
#PersistenceContext(unitName = "test-ejb", name = "persistence/em")
public Employee getEmployees() throws NamingException {
int empNo = 342;
Context context = new InitialContext();
context.lookup("java:comp/env");
EntityManager em = (EntityManager)context.lookup("persistence/em");
return em.find(Employee.class, empNo);
}
persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<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_1_0.xsd" version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="test-ejb" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/testDS</jta-data-source>
<class>test.entity.Employees</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="eclipselink.target-server" value="OC4J"/>
<property name="javax.persistence.target-database" value="Oracle"/>
<property name="javax.persistence.logging.parameters" value="TRUE"/>
</properties>
</persistence-unit>
</persistence>
Exception stack
javax.naming.NameNotFoundException: persistence/em not found
at com.evermind[Oracle Containers for J2EE 10g (10.1.3.5.0) ].server.rmi.RMIServerContext.lookup(RMIServerContext.java:207)
at com.evermind[Oracle Containers for J2EE 10g (10.1.3.5.0) ].server.ApplicationContext.unprivileged_lookup(ApplicationContext.java:256)
at com.evermind[Oracle Containers for J2EE 10g (10.1.3.5.0) ].server.ApplicationContext.lookup(ApplicationContext.java:196)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at test.dao.EmployeeDAO.getValues(EmployeeDAO.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1511)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1442)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1391)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1381)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:538)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:716)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
at com.evermind[Oracle Containers for J2EE 10g (10.1.3.5.0) ].server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:734)
at com.evermind[Oracle Containers for J2EE 10g (10.1.3.5.0) ].server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:391)
at com.evermind[Oracle Containers for J2EE 10g (10.1.3.5.0) ].server.http.HttpRequestHandler.doProcessRequest(HttpRequestHandler.java:908)
at com.evermind[Oracle Containers for J2EE 10g (10.1.3.5.0) ].server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:458)
at com.evermind[Oracle Containers for J2EE 10g (10.1.3.5.0) ].server.http.HttpRequestHandler.serveOneRequest(HttpRequestHandler.java:226)
at com.evermind[Oracle Containers for J2EE 10g (10.1.3.5.0) ].server.http.HttpRequestHandler.run(HttpRequestHandler.java:127)
at com.evermind[Oracle Containers for J2EE 10g (10.1.3.5.0) ].server.http.HttpRequestHandler.run(HttpRequestHandler.java:116)
at oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:260)
at com.evermind[Oracle Containers for J2EE 10g (10.1.3.5.0) ].util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303)
at java.lang.Thread.run(Thread.java:662)
Update 1
#Stateless
#LocalBean
public class EmployeeDAO {
#PersistenceContext(unitName = "test-ejb", name = "persistence/em")
public Employee getEmployees() throws NamingException {
int empNo = 342;
Context context = new InitialContext();
context.lookup("java:comp/env");
EntityManager em = (EntityManager)context.lookup("persistence/em");
return em.find(Employee.class, empNo);
}
Exception
javax.ejb.EJBException: Setter injection being applied to non-setter method: getValues; nested exception is: java.lang.InstantiationException: Setter injection being applied to non-setter method: getValues
Full stack
Caused by: java.lang.InstantiationException: Setter injection being applied to non-setter method: getValues
at com.evermind.server.deployment.J2EEContextAnnotationParser.validateInjectionSetter(J2EEContextAnnotationParser.java:713)
at com.evermind.server.deployment.J2EEContextAnnotationParser.createInjectionTarget(J2EEContextAnnotationParser.java:729)
at com.evermind.server.deployment.J2EEContextAnnotationParser.parseInjectedMethod(J2EEContextAnnotationParser.java:378)
at com.evermind.server.ejb.deployment.BeanDescriptorAnnotationParser.parseInjectedMethodAndCallbacks(BeanDescriptorAnnotationParser.java:276)
at com.evermind.server.ejb.deployment.SessionBeanDescriptorAnnotationParser.parseInjectedMethodAndCallbacks(SessionBeanDescriptorAnnotationParser.java:95)
at com.evermind.server.ejb.deployment.BeanDescriptorAnnotationParser.parseAnnotations(BeanDescriptorAnnotationParser.java:77)
at com.evermind.server.ejb.deployment.BeanDescriptorAnnotationParser.parseAnnotations(BeanDescriptorAnnotationParser.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.evermind.server.ejb.BeanAnnotationListener.parseAnnotatedClass(BeanAnnotationListener.java:45)

Change:
public class EmployeeDAO {
#PersistenceContext(unitName = "test-ejb", name = "persistence/em")
...
to:
#PersistenceContext(unitName = "test-ejb", name = "persistence/em")
#Stateless
public class EmployeeDAO {
...

EmployeeDAO must be a container-managed class (listener, filter, servlet, EJB, managed bean, CDI managed bean, etc.), not a POJO. The JPA container will only search for JPA annotations on container-managed classes, not on POJOs.
Your options are:
Change EmployeeDAO to be a container-managed class. For example, if your application server supports EJBs, then add the #Stateless annotation to the class.
Move the #PersistenceContext annotation to a container-managed class. For example, if you have an existing listener, filter, or servlet, move the annotation to that class.
Add <persistence-context-ref> to web.xml.
Note, your application server must support container-managed JPA for any of these approaches to work.

Related

EclipseLink 3.0 doesn't find a suitable jdbc (Jakarta EE)

I'm trying to run a simple web application on which I want run some tests on Jakarta EE 9.1(Full platform). I deployed my application on Glassfish 6.2.5. While I was running some code with jpa implementation this exception is thrown(the persistence provider is EclipseLink 3.0.2):
jakarta.persistence.PersistenceException: Exception [EclipseLink-4002]
(Eclipse Persistence Services - 3.0.2.v202107160933):
org.eclipse.persistence.exceptions.DatabaseException Internal
Exception: java.sql.SQLException: No suitable driver found for
jdbc:mysql://localhost:3306;create=true Error Code: 0
The persistence.xml is:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd"
version="3.0">
<persistence-unit name="GestoreDB" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>testJPA.ValueBeen</class>
<properties>
<property name="jakarta.persistence.schema-generation.action" value="drop-and-create"/>
<property name="jakarta.persistence.schema-generation.scripts.create-target" value="database-and-scripts"/>
<property name="jakarta.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306;create=true"/>
<property name="jakarta.persistence.jdbc.user" value="root"/>
<property name="jakarta.persistence.jdbc.password" value="myPwd"/>
</properties>
</persistence-unit>
</persistence>
The Entity is(getters and setters omitted):
#Entity
#NamedQuery(name = "ValueBeen.selectTable", query = "select u from ValueBeen u")
public class ValueBeen
{
public ValueBeen(){
}
public ValueBeen(String value)
{
this.value = value;
}
public ValueBeen(int id, String value)
{
this.id = id;
this.value = value;
}
#Id
#GeneratedValue
private int id;
#NotNull
private String value;
...
}
And the WebServlet who perform persistency is:
#WebServlet(name = "helloServlet", value = "/hello-servlet")
public class HelloServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
ValueBeen valueBeen=new ValueBeen("Hello");
//Manager persistence and manager been
EntityManagerFactory managerPersistence = Persistence.createEntityManagerFactory("GestoreDB");
EntityManager entityManager = managerPersistence.createEntityManager();
//Do persistence
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
entityManager.persist(valueBeen);
transaction.commit();
//close managers
entityManager.close();
managerPersistence.close();
}
}
I put the jdbc connector jar (Mysql connector 8.0.28) in .\glassfish-6.2.5\glassfish\domains\domain1\lib
As you deploy your app to glassfish container then "transaction-type" in persistence.xml i guess should be "JTA", and property "jakarta.persistence.jdbc.url" is invalid because you do not indicate any database / schema name after ":3306". Glassfish documentation provides instructions and examples how to setup global jdbc connections and those limited to only application scope.

Multiple datasources in war: Unable to acquire JDBC Connection

Environment:
Wildfly 10
Java 8
I have a war project with a persistence unit(OracleDS) that access to a ejb.jar with another persistence unit(MySqlDS).
The server has configured both datasources as Non-XA.
The default transaction management is type Container, but if I use Transaction ManagementType.BEAN at class level it seems to work.
Why is that working? WHat is the difference with the Container type?
Code in #Stateless class
public void test() {
Espacio espacioBase = espacioMgr.findByCodEspai(1); //EJB with 1st datasource
Servei servei = ServeiMgr.findById(1); //EJB with 2nd datasource ERROR
}
Espacio.java new.war
#Entity
#Table(name = "V_ESPACIOS")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = Espacio.findByCodEspai, query = "SELECT e FROM Espacio e WHERE e.codespai = :codespai")})
public class Espacio implements Serializable {
private static final long serialVersionUID = 1L;
public static final String findByTipus = "Espacio.findByTipus";
public static final String findByCodEspaiPare = "Espacio.findByCodEspaiPare";
public static final String findByNom = "Espacio.findByNom";
public static final String findAll = "Espacio.findAll";
public static final String findByCodEspai = "Espacio.findByCodEspai";
public static final String findChildrenByCodEspai = "Espacio.findChildrenByCodEspai";
...
Servei.java ejb.jar
#Entity
#Table(name = "a_servei")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = Servei.findAll, query = "SELECT s FROM Servei s")})
public class Servei implements Serializable, Comparable<Servei> {
private static final long serialVersionUID = -1979740551238968079L;
static final String PREFIX = "pia.entity.Servei.";
public static final String findAll = PREFIX + "findAll";
...
ServeiManager
#Stateless
public class ServeiManager {
protected Logger logger = Logger.getLogger(getClass().getName());
#PersistenceContext(unitName = "onePU")
protected EntityManager em;
public List<Servei> all() {
return this.em.createNamedQuery(Servei.findAll, Servei.class).
getResultList();
}
...
EspacioManager
#Stateless
public class EspacioManager {
protected Logger logger = Logger.getLogger(getClass().getName());
#PersistenceContext(unitName = "twoPU")
protected EntityManager em;
public Espacio findByCodEspai(int codEspai) {
return this.em.createNamedQuery(Espacio.findByCodEspai, Espacio.class).
setParameter("codespai", codEspai).
getSingleResult();
}
...
persistence.xml new.war
<?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="twoPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/jboss/datasources/OracleDS</jta-data-source>
<properties>
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.driver.OracleDriver"/>
</properties>
</persistence-unit>
</persistence>
persistence.xml ejb.jar
<?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="onePU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/MySqlDS</jta-data-source>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
</persistence>
Error
09:24:46,961 WARN [com.arjuna.ats.arjuna] (default task-18) ARJUNA012140: Adding multiple last resources is disallowed. Trying to add LastResourceRecord(XAOnePhaseResource(LocalXAResourceImpl#425d04d5[connectionListener=1949f99c connectionManager=76ebb8c8 warned=false currentXid=< formatId=131077, gtrid_length=29, bqual_length=36, tx_uid=0:ffff7f000101:2b71c2d2:5a701dd6:13d, node_name=1, branch_uid=0:ffff7f000101:2b71c2d2:5a701dd6:143, subordinatenodename=null, eis_name=java:jboss/datasources/MySqlDS > productName=MySQL productVersion=5.5.44-MariaDB-log jndiName=java:jboss/datasources/MySqlDS])), but already have LastResourceRecord(XAOnePhaseResource(LocalXAResourceImpl#47bca654[connectionListener=2b07cb93 connectionManager=214b627a warned=false currentXid=< formatId=131077, gtrid_length=29, bqual_length=36, tx_uid=0:ffff7f000101:2b71c2d2:5a701dd6:13d, node_name=1, branch_uid=0:ffff7f000101:2b71c2d2:5a701dd6:141, subordinatenodename=null, eis_name=java:jboss/datasources/OracleDS > productName=Oracle productVersion=Oracle Database 11g Release 11.2.0.4.0 - 64bit Production
With the Automatic Storage Management option jndiName=java:jboss/datasources/OracleDS]))
09:24:46,966 WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-18) SQL Error: 0, SQLState: null
09:24:46,967 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-18) javax.resource.ResourceException: IJ000457: Unchecked throwable in managedConnectionReconnected() cl=org.jboss.jca.core.connectionmanager.listener.TxConnectionListener#1949f99c[state=NORMAL managed connection=org.jboss.jca.adapters.jdbc.local.LocalManagedConnection#33011f78 connection handles=0 lastReturned=1517300686965 lastValidated=1517297117411 lastCheckedOut=1517300686959 trackByTx=false pool=org.jboss.jca.core.connectionmanager.pool.strategy.OnePool#35406018 mcp=SemaphoreConcurrentLinkedQueueManagedConnectionPool#2e374d12[pool=MySqlDS] xaResource=LocalXAResourceImpl#425d04d5[connectionListener=1949f99c connectionManager=76ebb8c8 warned=false currentXid=null productName=MySQL productVersion=5.5.44-MariaDB-log jndiName=java:jboss/datasources/MySqlDS] txSync=null]
09:24:46,970 INFO [org.hibernate.event.internal.DefaultLoadEventListener] (default task-18) HHH000327: Error performing load command : org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
09:24:47,057 ERROR [org.jboss.as.ejb3.invocation] (default task-18) WFLYEJB0034: EJB Invocation failed on component ServeiManager for method public es.imas.ada.business.gestio.entity.Servei es.imas.ada.business.gestio.boundary.ServeiManager.findById(int): javax.ejb.EJBTransactionRolledbackException: org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
... more
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
... more
Caused by: org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
... more
Caused by: java.sql.SQLException: javax.resource.ResourceException: IJ000457: Unchecked throwable in managedConnectionReconnected() cl=org.jboss.jca.core.connectionmanager.listener.TxConnectionListener#1949f99c[state=NORMAL managed connection=org.jboss.jca.adapters.jdbc.local.LocalManagedConnection#33011f78 connection handles=0 lastReturned=1517300686965 lastValidated=1517297117411 lastCheckedOut=1517300686959 trackByTx=false pool=org.jboss.jca.core.connectionmanager.pool.strategy.OnePool#35406018 mcp=SemaphoreConcurrentLinkedQueueManagedConnectionPool#2e374d12[pool=MySqlDS] xaResource=LocalXAResourceImpl#425d04d5[connectionListener=1949f99c connectionManager=76ebb8c8 warned=false currentXid=null productName=MySQL productVersion=5.5.44-MariaDB-log jndiName=java:jboss/datasources/MySqlDS] txSync=null]
... 240 more
Caused by: javax.resource.ResourceException: IJ000457: Unchecked throwable in managedConnectionReconnected() cl=org.jboss.jca.core.connectionmanager.listener.TxConnectionListener#1949f99c[state=NORMAL managed connection=org.jboss.jca.adapters.jdbc.local.LocalManagedConnection#33011f78 connection handles=0 lastReturned=1517300686965 lastValidated=1517297117411 lastCheckedOut=1517300686959 trackByTx=false pool=org.jboss.jca.core.connectionmanager.pool.strategy.OnePool#35406018 mcp=SemaphoreConcurrentLinkedQueueManagedConnectionPool#2e374d12[pool=MySqlDS] xaResource=LocalXAResourceImpl#425d04d5[connectionListener=1949f99c connectionManager=76ebb8c8 warned=false currentXid=null productName=MySQL productVersion=5.5.44-MariaDB-log jndiName=java:jboss/datasources/MySqlDS] txSync=null]
... 244 more
Caused by: javax.resource.ResourceException: IJ000461: Could not enlist in transaction on entering meta-aware object
... 246 more
Caused by: javax.transaction.SystemException: IJ000356: Failed to enlist: java.lang.Throwable: Unabled to enlist resource, see the previous warnings. tx=TransactionImple < ac, BasicAction: 0:ffff7f000101:2b71c2d2:5a701dd6:13d status: ActionStatus.ABORT_ONLY >
... 247 more

javax.ejb.CreateException: Could not create stateless EJB with glassfish and boneCP on intellij-idea

I recently began to use Glassfish and boneCP on intellij idea with a simple web app, but there's a bug I can't understand. I believe I followed all the steps in the tutorial.
My model goes like this
#Entity
public class Song implements Serializable {
#Id
private String id;
private String title;
private LocalDate lastPlayed;
private int playCount;
public Song() {
title = "Chant sans titre";
id = generateId(title);
lastPlayed = LocalDate.ofEpochDay(0);
playCount = 0;
}
The EJB
#Stateless
public class SongDAO {
#PersistenceUnit(unitName = "statisthira_song")
private EntityManager em;
public void create(Song song){
try {
em.persist(song); } catch (Exception e) { e.printStackTrace(); }
}
the Servlet
#WebServlet(urlPatterns = "/new-song")
public class NewSongActionBean extends HttpServlet {
#EJB
SongDAO dao;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Song song = new Song();
song.setTitle("This is not a Test - Toby Mac");
song.setId(song.generateId(song.getTitle()));
dao.create(song);
this.getServletContext().getRequestDispatcher("/WEB-INF/newsong.jsp").forward(request, response);
}
}
My persistence.xml file under META-INF
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0"
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="statisthira_song" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/bonecp_resource</jta-data-source>
<class>statis.hira.model.Song</class>
</persistence-unit>
</persistence>
the server runs without any problem, and when I check the jdbc connection pool with a ping, it succeeds. But when I try to access the url "/new-song", I get this error message
HTTP Status 500 - Internal Server Error
type Exception report
message Internal Server Error
description The server encountered an internal error that prevented it from fulfilling this request.
exception javax.ejb.EJBException: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
here's a sample of the stacktrace
javax.ejb.EJBException: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:435)
at com.sun.ejb.containers.BaseContainer.getContext(BaseContainer.java:2579)
at com.sun.ejb.containers.BaseContainer.preInvoke(BaseContainer.java:1971)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:210)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy194.create(Unknown Source)
at statis.hira.dao.__EJB31_Generated__SongDAO__Intf____Bean__.create(Unknown Source)
at statis.hira.servlets.NewSongActionBean.doGet(NewSongActionBean.java:26)
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:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
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:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
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:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
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:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:700)
at com.sun.ejb.containers.util.pool.NonBlockingPool.getObject(NonBlockingPool.java:246)
at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:430)
... 37 more
Caused by: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:514)
at com.sun.ejb.containers.StatelessSessionContainer.access$000(StatelessSessionContainer.java:97)
at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:698)
... 39 more
Caused by: java.lang.IllegalStateException: Exception attempting to inject Env-Prop: statis.hira.dao.SongDAO/em#Field-Injectable Resource. Class name = statis.hira.dao.SongDAO Field name=em#java.lang.String### into class statis.hira.dao.SongDAO: Can not set javax.persistence.EntityManager field statis.hira.dao.SongDAO.em to com.sun.enterprise.container.common.impl.EntityManagerFactoryWrapper
at org.glassfish.weld.services.InjectionServicesImpl.aroundInject(InjectionServicesImpl.java:175)
at org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:46)
at org.jboss.weld.injection.producer.DefaultInjector.inject(DefaultInjector.java:73)
at org.jboss.weld.injection.producer.StatelessSessionBeanInjector.inject(StatelessSessionBeanInjector.java:60)
at org.jboss.weld.injection.producer.ejb.SessionBeanInjectionTarget.inject(SessionBeanInjectionTarget.java:140)
at org.glassfish.weld.services.JCDIServiceImpl.injectEJBInstance(JCDIServiceImpl.java:257)
at com.sun.ejb.containers.BaseContainer.injectEjbInstance(BaseContainer.java:1748)
at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:475)
... 41 more
Caused by: com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting to inject Env-Prop: statis.hira.dao.SongDAO/em#Field-Injectable Resource. Class name = statis.hira.dao.SongDAO Field name=em#java.lang.String### into class statis.hira.dao.SongDAO: Can not set javax.persistence.EntityManager field statis.hira.dao.SongDAO.em to com.sun.enterprise.container.common.impl.EntityManagerFactoryWrapper
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:740)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.inject(InjectionManagerImpl.java:507)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.injectInstance(InjectionManagerImpl.java:170)
at org.glassfish.weld.services.InjectionServicesImpl.aroundInject(InjectionServicesImpl.java:165)
... 48 more
Caused by: java.lang.IllegalArgumentException: Can not set javax.persistence.EntityManager field statis.hira.dao.SongDAO.em to com.sun.enterprise.container.common.impl.EntityManagerFactoryWrapper
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
at java.lang.reflect.Field.set(Field.java:764)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:688)
... 51 more
You should change from
#PersistenceUnit(unitName = "statisthira_song")
to
#PersistenceContext(name= "statisthira_song")
#PersistenceUnit is used to inject EntityManagerFactory and #PersistenceContext is used to inject EntityManager

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

I'm beginning Java EE with NetBeans 8.1, Glassfish 4.1 and Apache Derby (included in GlassFish).
For this purpose I'm calling to put and store a car data with its attributes.
But this simple facade always returns "java.lang.IllegalStateException" whereas I'm seeing no mistakes in my Class files.
Here is the very simple Entity of model.car with basic getters and setters :
#Entity
#Table(name = "car")
public class Car implements java.io.Serializable {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer id;
private String brand;
private String model;
private String year;
private String energy;
private String hp;
private String tp;
private byte[] picture;
Here is the "Facade" for this Entity to store data in Apache Derby :
#Stateless
public class CarFacade extends AbstractFacade<Car> {
#PersistenceContext(unitName = "CarLocPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public CarFacade() {
super(Car.class);
}
}
I'm having a lot of trouble debugging the following exception since it is very simple short part of code and everything should works fine. Moreover, the StackTrace doesn't show the breaking point like in Java SE.
Here is the exception StackTrace :
Caused by: java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName CarLocPU
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.init(EntityManagerWrapper.java:138)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTxRequiredCheck(EntityManagerWrapper.java:158)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTransactionScopedTxCheck(EntityManagerWrapper.java:151)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:281)
at facade.AbstractFacade.create(AbstractFacade.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:64)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
at sun.reflect.GeneratedMethodAccessor965.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.GeneratedMethodAccessor994.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
... 53 more
Thank you in advance for you help.
EDIT :
Here is the structure of the project.
And here is the persistence.xml content, the application is named "CarLoc".
<?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="CarLocPU" transaction-type="JTA">
<jta-data-source>java:app/jdbc/CarLoc</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
If you are using JPA outside of the EJB container, you need to declare a JPA <provider> in your persistence.xml.
By default Glassfish uses EclipseLink as the JPA provider. Assuming you don't want to change this, you will want to change your persistence.xml to declare EclipseLink as the JPA provider:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="CarLocPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.target-database" value="Derby"/>
<!-- JDBC connection properties -->
<property name="eclipselink.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="eclipselink.jdbc.url" value="jdbc:derby://localhost:1527/myDBName;create=true;"/>
<property name="eclipselink.jdbc.user" value="APP"/>
<property name="eclipselink.jdbc.password" value="APP"/>
</properties>
</persistence-unit>
</persistence>
Source:
Oracle Docs - Chapter 7 Using the Java Persistence API

Eclipselink: No suitable driver found in glassfish while it works in JavaSE

I'm trying to create EntityManager in my webapp, but it's failing with:
No suitable driver found for jdbc:postgresql:://localhost/database
However the same persistance unit and the same code for creating EntityManager works when I run it as JavaSE console application (from main() ).
Googling gave me several common problems causing that error:
JDBC url is wrong
Shouldn't be since it works from main
JDBC Driver is not in the class path
I can create a Class object using Class.forName("org.postgresql.Driver"); for the driver so I think it is in the classpath.
Other things I tried:
I thought maybe the driver jar from glassfish/lib and the webapp/WEB-INF/lib are conflicting somehow so I tried with both of them together and separately, no luck.
Recreated a small new webapp hoping the problem will go away, it didn't :-)
Inject #PersistanceUnit - also didn't work, don't know is it the same issue or I didn't use it properly as I'm still learning about injection and EJBs
Thanks
Full error:
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: java.sql.SQLException: No suitable driver found for jdbc:postgresql://localhost/database Error Code: 0
Here is the code:
ManagedBean in webapp:
#ManagedBean
public class TestBean {
private String entry;
private String driver;
public String getFromDatabase(){
EntityManagerFactory emf = Persistence.createEntityManagerFactory("Unit1");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
EntityOne one = new EntityOne();
one.id = 1;
one.entry = "Bla bla";
em.persist(one);
tx.commit();
em.close();
return "done";
}
public String createDriver(){
try {
Class d = Class.forName("org.postgresql.Driver");
driver = d.getName();
} catch (ClassNotFoundException e) {
driver = "Class not found";
return "";
}
return "";
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getEntry() {
return entry;
}
public void setEntry(String entry) {
this.entry = entry;
}
}
Same code working in main:
public class Standalone {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("Unit1");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
EntityOne one = new EntityOne();
one.id = 1;
one.entry = "Bla bla";
em.persist(one);
tx.commit();
em.close();
}
}
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="Unit1" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.test.EntityOne</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost/database"/>
<property name="javax.persistence.jdbc.user" value="darko"/>
<property name="javax.persistence.jdbc.password" value="sifra"/>
<property name="eclipselink.target-database" value="PostgreSQL"/>
</properties>
</persistence-unit>
Place the posgres jdbc driver into the lib of glassfish. Its something like this.
[glassfish_home]/glassfish/domains/YOUR_DOMAIN/lib/
Also, restart the server after this.