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
Related
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.
I'm having difficulties to persist UserEntitys on my JavaDB from an ejb Project. I tried a couple of solutions from various google searches but non seem to help me.
I'm using GlassFish 4 and the JavaDB which comes with it.
This is my Statlessbean which needs the EntityManager
It should be injected by the container through #PersistenceContext as far as I understand.
#Stateless
public class UserManagementBean implements UserManagementLocal, UserManagementRemote {
#PersistenceContext(unitName = "ChatDB")
private EntityManager entityManager;
#EJB
private ChatManagementLocal chatManagement;
#EJB
private StatisticManagementLocal statisticManagement;
//...
#Override
public void login(String username, String password) throws Exception {
//...
}
#Override
public void logout(String username) {
//...
}
#Override
public void registerUser(String username, String password) throws Exception {
TypedQuery<UserEntity> query = entityManager.createNamedQuery("UserEntity.singleUser", UserEntity.class);
query.setParameter("username", username);
UserEntity foundUser;
try {
foundUser = query.getSingleResult();
} catch (NoResultException e) {
foundUser = new UserEntity();
foundUser.setLoggedIn(false);
foundUser.setUsername(username);
foundUser.setPassword(generateHash(password));
entityManager.persist(foundUser);
chatManagement.sendRegisterMessage(username);
}
throw new Exception("Der Benutzername ist bereits vergeben.");
}
public String generateHash(String password { ... }
}
project-ejb
--META-INF
----persistance.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">
<persistence-unit name="ChatDB" transaction-type="JTA">
<jta-data-source>java:app/jdbc/ChatDB</jta-data-source>
<jar-file>Chat-common.jar</jar-file>
<properties>
<property name="eclipselink.target-database" value="Derby"/>
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
<property name="eclipselink.logging.level" value="INFO"/>
</properties>
</persistence-unit>
</persistence>
project-ear
--META-INF
----glassfish-resources.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC
"-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN"
"http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
<jdbc-connection-pool name="ChatDBPool"
res-type="javax.sql.ConnectionPoolDataSource"
datasource-classname="org.apache.derby.jdbc.ClientDataSource">
<property name="serverName" value="localhost" />
<property name="port" value="1527" />
<property name="databaseName" value="chat" />
<property name="connectionAttributes" value=";create=true"></property>
<property name="user" value="APP" />
<property name="password" value="APP" />
</jdbc-connection-pool>
<jdbc-resource enabled="true"
jndi-name="java:app/jdbc/ChatDB"
pool-name="ChatDBPool" />
</resources>
Console
javax.ejb.EJBException
at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:752)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:702)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:507)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4566)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2074)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2044)
at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBObjectInvocationHandlerDelegate.invoke(EJBObjectInvocationHandlerDelegate.java:79)
at com.sun.proxy.$Proxy286.registerUser(Unknown Source)
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:498)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie.dispatchToMethod(ReflectiveTie.java:143)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:173)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
Caused by: java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName ChatDB
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.init(EntityManagerWrapper.java:138)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper._getDelegate(EntityManagerWrapper.java:171)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.createNamedQuery(EntityManagerWrapper.java:544)
at de.fh_dortmund.inf.cw.chat.server.beans.UserManagementBean.registerUser(UserManagementBean.java:146)
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:498)
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:73)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
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:498)
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.GeneratedMethodAccessor71.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
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.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:205)
... 19 more
At this point I have no idea on how to start on this issue, what have I missed? What should I check? What further details do you need?
This:
project-ejb
--META-INF
----persistance.xml
looks suspicious.
You appear to have mis-spelt "persistence.xml".
I am using Glassfish 4.1.1 and MySQL. I have a table named customer and a class named Customer. When I use JSF and a controller to persist newly entered customer data I get the error: java.lang.IllegalArgumentException: Object: model.Customer#e5202 is not a known Entity type.I checked other posts that hat the same error message but I have all the annotations and entries in the persistence.xml that helped others . Help greatly appreciated since I've been stuck on this for quite a while.
my Customer class that I essentially generated from Mysql via the Eclipsa JPA Wizard goes like this:
#Entity
#Model
#NamedQuery(name="Customer.findAll", query="SELECT c FROM Customer c")
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
In the controller where the error occurs the code is this:
#Named
#SessionScoped
#ManagedBean(name="customerController")
public class CustomerController implements Serializable {
private static final long serialVersionUID=1L;
#PersistenceContext
private EntityManager em;
#Inject
private Customer customer;
#Resource
private UserTransaction ut;
public String save(){
try{
ut.begin();
em.persist(customer);
ut.commit();
}
catch(Exception e){
Logger log = Logger.getLogger("Shop");
log.logp(Level.SEVERE, this.getClass().toString(), "save()", "customer could not be persisted.", e);
}
My persistance.xml goes like this:
<?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="PrintCenterAdmin" transaction-type="JTA">
<!-- some classes included-->
<class>model.Customer</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
</persistence-unit>
</persistence>
Here the full blown stacktrace
java.lang.IllegalArgumentException: Object: model.Customer#4b4638 is not a known Entity type.
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4226)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:507)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:287)
at controllers.CustomerController.save(CustomerController.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at javax.el.ELUtil.invokeMethod(ELUtil.java:332)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:537)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
at com.sun.el.parser.AstValue.invoke(AstValue.java:283)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
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(Unknown Source)
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.
I have a problem with Java Persistence API and Hibernate.
My situation of project is:
My persistence.xml file is:
<persistence
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"
version="2.0">
<persistence-unit name="JPA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.david.Libro</class>
<class>com.david.Categoria</class>
<properties>
<property name="hibernate.show_sql" value="true" />
<property name="javax.persistence.transactionType" value="RESOURCE_LOCAL" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/arquitecturaJava" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
</properties>
</persistence-unit>
</persistence>
And i create EntityManagerFactory in:
private static EntityManagerFactory buildEntityManagerFactory()
{
try
{
return Persistence.createEntityManagerFactory("JPA");
}
catch (Throwable ex)
{
ex.printStackTrace();
//throw new RuntimeException("Error al crear la factoria de JPA:->"+ ex.getMessage());
}
}
My error is about create EntityManagerFactory:
javax.persistence.PersistenceException: [PersistenceUnit: JPA] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:924)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:899)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:59)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:63)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
at com.david.JPAHelper.buildEntityManagerFactory(JPAHelper.java:14)
at com.david.JPAHelper.<clinit>(JPAHelper.java:8)
at com.david.Categoria.buscarTodos(Categoria.java:93)
at com.david.FormularioInsertarLibroAccion.ejecutar(FormularioInsertarLibroAccion.java:25)
at com.david.ControladorLibros.doGet(ControladorLibros.java:38)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.DuplicateMappingException: Duplicate class/entity mapping com.david.Libro
at org.hibernate.cfg.Configuration$MappingsImpl.addClass(Configuration.java:2638)
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:706)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3512)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3466)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1355)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1756)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:96)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:914)
... 27 more
Part of Libro and Categoria classes code is:
#Entity
#Table(name = "Categorias")
public class Categoria implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#JoinColumn(name = "categoria")
private String id;
private String descripcion;
....
and
#Entity
#Table(name="Libros")
public class Libro implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
private String isbn;
private String titulo;
#ManyToOne
#JoinColumn (name="categoria")
private Categoria categoria;
....
My file of Hibernate Configuration is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/arquitecturajava</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.pool_size">5</property>
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">true</property>
<mapping class="com.david.Categoria"></mapping>
<mapping class="com.david.Libro"></mapping>
</session-factory>
</hibernate-configuration>
Any ideas!!
ThankĀ“s!!
You don't need both hibernate.cfg.xml and persistence.xml in this case. Have you tried removing hibernate.cfg.xml and mapping everything in persistence.xml only?
But as the other answer also pointed out, this is not okay like this:
#Id
#JoinColumn(name = "categoria")
private String id;
Didn't you want to use #Column instead?
Suppress the #JoinColumn(name="categoria") on the ID field of the Categoria class and I think it will work.
Use above annotation if someone is facing :--org.hibernate.jpa.HibernatePersistenceProvider persistence provider when it attempted to create the container entity manager factory for the paymentenginePU persistence unit. The following error occurred: [PersistenceUnit: paymentenginePU] Unable to build Hibernate SessionFactory
** This is a solution if you are using Audit table.#Audit
Use:- #Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) on superclass.
It worked for me after adding the following dependency in pom,
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>