I have the next problem while trying to develope a REST app using JPA and EJB's.
I have 3 projects in NetBeans (same workspace, just projects, not EAR or that weird stuff):
One of them is a Java Application in which I created some entity classes from a database. Inside of the same project, I created other package containing the controller classes from the entities. I tested the project creating a java main class and using the controllers.
The other project is a EJB module, it as simple as a package and the next class inside of it:
package com.studentejb;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import studentdao.StudentTO;
import studentdao.StudentJpaController;
#Stateless
#LocalBean
public class StudentEJB {
private StudentJpaController studentDao = new StudentJpaController();
public List<StudentTO> findStudents() {
return studentDao.findStudentTO();
}
}
As you can see, I imported the previous JAR project (the one with the entity's controllers). I also tested this EJB project with a java main class and it worked.
The last project is a web application, as you can imagine I want to use the EJB modules of the previous project but I get the following errors while trying to enter to the resource http://localhost:8080/studentWeb/student/:
12:00:12,384 ERROR [io.undertow.request] (default task-2) UT005023: Exception handling request to /studentWeb/student/hola: com.google.common.util.concurrent.ExecutionError: java.lang.ExceptionInInitializerError
at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2201)
at com.google.common.cache.LocalCache.get(LocalCache.java:3937)
at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3941)
at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4824)
at org.jboss.weld.util.cache.LoadingCacheUtils.getCacheValue(LoadingCacheUtils.java:49)
.
.
.
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ExceptionInInitializerError
at studentdao.StudentJpaController.<init>(StudentJpaController.java:40)
at com.studentejb.StudentEJB.<init>(StudentEJB.java:23)
at com.studentweb.Resources.<init>(Resources.java:52)
at com.studentweb.Resources$Proxy$_$$_WeldClientProxy.<init>(Unknown Source)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
.
.
.
... 58 more
Caused by: javax.persistence.PersistenceException: Unable to locate persistence units
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:99)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:86)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:67)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at studentdao.EntityProvider.<clinit>(EntityProvider.java:20)
... 80 more
Caused by: javax.persistence.PersistenceException: Invalid persistence.xml.
Error parsing XML [line : -1, column : -1] : cvc-elt.1.a: Cannot find the declaration of element 'persistence'.
at org.hibernate.jpa.boot.internal.PersistenceXmlParser.validate(PersistenceXmlParser.java:377)
at org.hibernate.jpa.boot.internal.PersistenceXmlParser.loadUrl(PersistenceXmlParser.java:310)
at org.hibernate.jpa.boot.internal.PersistenceXmlParser.parsePersistenceXml(PersistenceXmlParser.java:114)
at org.hibernate.jpa.boot.internal.PersistenceXmlParser.doResolve(PersistenceXmlParser.java:104)
at org.hibernate.jpa.boot.internal.PersistenceXmlParser.locatePersistenceUnits(PersistenceXmlParser.java:86)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:95)
... 85 more
Here is the code of the web app (Resources.java):
#Path("/student")
public class Resources {
#EJB
private StudentEJB studentEjb;
#Context
private UriInfo context;
public Resources() throws FileNotFoundException, IOException, NamingException {
studentEjb = new StudentEJB();
}
#GET
#Path("/")
#Produces(MediaType.APPLICATION_JSON)
public Response getJson() {
return Response.ok(studentEjb.findStudents()).build();
}
}
So I am using 2 JARs for the web project, the one with the EJB modules and the other with the entities and controllers..
Here is the persistence.xml generated by the JPA project:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://xmlns.jcp.org/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="studentJPAPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<!-- <provider>org.hibernate.ejb.HibernatePersistence</provider> -->
<class>studentjpa.Address</class>
<class>studentjpa.Phone</class>
<class>studentjpa.Student</class>
<class>studentjpa.Email</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://localhost:1433;databaseName=tca_student_db;integratedSecurity=true"/>
<property name="javax.persistence.jdbc.user" value="xxxx"/>
<property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="javax.persistence.jdbc.password" value="xxxx"/>
</properties>
</persistence-unit>
</persistence>
Thank you!
Caused by: javax.persistence.PersistenceException: Invalid
persistence.xml. Error parsing XML [line : -1, column : -1] :
cvc-elt.1.a: Cannot find the declaration of element 'persistence'.
Here :
<persistence version="2.0" xmlns="http://xmlns.jcp.org/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">
xmlns :http://xmlns.jcp.org/xml/ns/persistence doesn't match with the namespace in xsischemaLocation which is http://java.sun.com/xml/ns/persistence
Try to use the same in both :
<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">
Related
Have put the persistence.xml in the classpath of the project in eclipse because before the error was that the file was not found. Now gives this error:
Caused by: javax.persistence.PersistenceException: Invalid persistence.xml. Error parsing XML [line : -1, column : -1] : cvc-elt.1: Can not find the declaration of element 'persistence'
here is my file:
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.1"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="DataSource" transaction-type="JTA">
<description>JTA persistence unit related to the datasource DataSource</description>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.ejb.cfgfile" value="hibernate_DataSource.cfg.xml"/>
</properties>
</persistence-unit>
<persistence-unit name="securityStore" transaction-type="JTA">
<description>JTA persistence unit related to the datasource securityStore</description>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.ejb.cfgfile" value="hibernate_securityStore.cfg.xml"/>
</properties>
</persistence-unit>
</persistence>
According to the JPA spec (see section 8.2.1 persistence.xml file):
A persistence.xml file defines a persistence unit. The persistence.xml file is located in the META-INF directory of the root of the persistence unit.
So, try to put your persistence.xml in the META-INF directory.
P.S. Maybe you application actually use not the persistence.xml what you expect, but placed somewhere in the classpath in META-INF directory.
I am currently working on getting MongoDB set up with my java play framework server and JPA. Right now I am having an error whereby any function annotated with #Transactional gets this error:
play.api.http.HttpErrorHandlerExceptions$$anon$1: Execution exception[[CompletionException: java.lang.IllegalStateException: Tried to remove the EntityManager, but none was set.]]
at play.api.http.HttpErrorHandlerExceptions$.throwableToUsefulException(HttpErrorHandler.scala:293)
at play.api.http.DefaultHttpErrorHandler.onServerError(HttpErrorHandler.scala:220)
at play.api.GlobalSettings$class.onError(GlobalSettings.scala:160)
at play.api.DefaultGlobal$.onError(GlobalSettings.scala:188)
at play.api.http.GlobalSettingsHttpErrorHandler.onServerError(HttpErrorHandler.scala:100)
at play.core.server.netty.PlayRequestHandler$$anonfun$2$$anonfun$apply$1.applyOrElse(PlayRequestHandler.scala:100)
at play.core.server.netty.PlayRequestHandler$$anonfun$2$$anonfun$apply$1.applyOrElse(PlayRequestHandler.scala:99)
at scala.concurrent.Future$$anonfun$recoverWith$1.apply(Future.scala:346)
at scala.concurrent.Future$$anonfun$recoverWith$1.apply(Future.scala:345)
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32)
Caused by: java.util.concurrent.CompletionException: java.lang.IllegalStateException: Tried to remove the EntityManager, but none was set.
at java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:292)
at java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:308)
at java.util.concurrent.CompletableFuture.uniApply(CompletableFuture.java:593)
at java.util.concurrent.CompletableFuture$UniApply.tryFire(CompletableFuture.java:577)
at java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:474)
at java.util.concurrent.CompletableFuture.completeExceptionally(CompletableFuture.java:1977)
at scala.concurrent.java8.FuturesConvertersImpl$CF.apply(FutureConvertersImpl.scala:21)
at scala.concurrent.java8.FuturesConvertersImpl$CF.apply(FutureConvertersImpl.scala:18)
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32)
at scala.concurrent.BatchingExecutor$Batch$$anonfun$run$1.processBatch$1(BatchingExecutor.scala:63)
Caused by: java.lang.IllegalStateException: Tried to remove the EntityManager, but none was set.
at play.db.jpa.JPAEntityManagerContext.pop(JPAEntityManagerContext.java:74)
at play.db.jpa.DefaultJPAApi.withTransaction(DefaultJPAApi.java:155)
at play.db.jpa.DefaultJPAApi.withTransaction(DefaultJPAApi.java:195)
at play.db.jpa.TransactionalAction.call(TransactionalAction.java:25)
at play.core.j.JavaAction$$anonfun$7.apply(JavaAction.scala:108)
at play.core.j.JavaAction$$anonfun$7.apply(JavaAction.scala:108)
at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24)
at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24)
at play.core.j.HttpExecutionContext$$anon$2.run(HttpExecutionContext.scala:56)
at play.api.libs.iteratee.Execution$trampoline$.execute(Execution.scala:70)
This error happens if and only if my method has #Transactional on it.
I added the correct dependencies to build.sbt:
libraryDependencies += javaJpa
libraryDependencies += "org.hibernate.ogm" % "hibernate-ogm-core" % "5.0.0.Final"
libraryDependencies += "org.hibernate.ogm" % "hibernate-ogm-mongodb" % "5.0.0.Final"
And I configured conf/META-INF/persitence.xml:
<persistence 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"
version="2.1">
<persistence-unit name="defaultPersistenceUnit" transaction-type="JTA">
<provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
<non-jta-data-source>DefaultDS</non-jta-data-source>
<properties>
<property name="hibernate.ogm.datastore.provider"
value="org.hibernate.ogm.datastore.mongodb.impl.MongoDBDatastoreProvider"/>
<property name="hibernate.ogm.datastore.host" value="127.0.0.1"/>
<property name="hibernate.ogm.datastore.port" value="27017"/>
<property name="hibernate.ogm.datastore.database" value="[DB name here]"/>
<property name="hibernate.ogm.datastore.safe" value="true"/>
</properties>
</persistence-unit>
</persistence>
And set my default persistance unit in conf/application.conf:
jpa.default=defaultPersistenceUnit
Here's my sample method:
#Transactional()
public Result put() {
Test tmp = play.libs.Json.fromJson(request().body().asJson(), Test.class);
JPA.em().persist(tmp);
return ok(play.libs.Json.toJson(tmp));
}
Well, having spent weeks on this, I feel stupid. The problem was Transaction type needed to be resource local like so:
<persistence-unit name="defaultPersistenceUnit" transaction-type="RESOURCE_LOCAL">
I am getting the following exception:
javax.el.ELException: javax.persistence.TransactionRequiredException
at com.sun.el.parser.AstValue.invoke(AstValue.java:279)
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)
Caused by: javax.persistence.TransactionRequiredException
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTxRequiredCheck(EntityManagerWrapper.java:161)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTransactionScopedTxCheck(EntityManagerWrapper.java:151)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:299)
I am using Hibernate 4.3.5
#Named
#SessionScoped
public class MenuBean implements Serializable {
#PersistenceContext
private EntityManager entityManager;
#Transactional
public void create() {
MenuTitle menu = new MenuTitle();
menu.setLabel(label);
entityManager.persist(menu); //exception in this line
label = null;
}
Persistence XML:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="MyPersistenceUnit" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>MySQL5</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.current_session_context_class" value="jta"/>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform"/>
<property name="hibernate.hbm2ddl.auto" value="none"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
</properties>
</persistence-unit>
I have also tried to set hibernate.transaction.jta.platform to org.hibernate.engine.transaction.jta.platform.internal.SunOneJtaPlatform but it results in the same error.
EJB CMT´s are working fine.
The Create action is called from a commandButton:
<p:commandButton value="Create" process="#this type" update=":megaMenuForm:mainMenu" actionListener="#{menuBean.create()}" oncomplete="closeMenuDialog(xhr, status, args)"/>
See EJB specs if you want to manage transaction. Inject a resource UserTransaction.
Also #Transactional with not do anything here since you are using EJB.
In general you example should work, and #Transactional annotation will be just ignored. Could you try to make an interface, and call create method through it?
Looks like you are using EJB 2 style coding, but Glassfish 4 implements EJB 3.1, so it is better to go with a new one.
I have a JAR file that needs to be deployed into multiple environments, each with their own database connection parameters. Rightly or wrongly, I've been requested to make those database connection parameters external to the JAR. I've seen examples where persistence.xml can reference an external hibernate.cfg.xml that contains the specific connection parameters. Here's my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="myApp" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.ejb.cfgfile" value="./hibernate.cfg.xml" />
</properties>
</persistence-unit>
</persistence>
That external hibernate.ejb.cfg is located in the same folder as the JAR file, but the reference is failing. Here's the error I get:
DEBUG Ejb3Configuration - Look up for persistence unit: myApp
DEBUG Ejb3Configuration - Detect class: true; detect hbm: true
DEBUG Ejb3Configuration - Detect class: true; detect hbm: true
DEBUG Ejb3Configuration - Creating Factory: myApp
ERROR MyDaoImpl - initEntityManager() exception:
javax.persistence.PersistenceException: [PersistenceUnit: myApp] Unable to configure EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:265)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:125)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:52)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:34)
at com.touchnet.MyApp.server.dao.MyDaoImpl.initEntityManager(MyDaoImpl.java:486)
at com.touchnet.MyApp.server.dao.MyDaoImpl.getEntityManager(MyDaoImpl.java:457)
at com.touchnet.MyApp.server.dao.MyDaoImpl.getTransaction(MyDaoImpl.java:512)
at com.touchnet.MyApp.server.dao.MyDaoImpl.beginTransaction(MyDaoImpl.java:502)
at com.touchnet.MyApp.server.service.MyAppService.loadInputFile(MyAppService.java:346)
at com.touchnet.MyApp.server.commandLine.MyAppLoader.main(MyAppLoader.java:74)
at com.touchnet.MyApp.server.commandLine.MyAppLauncher.main(MyAppLauncher.java:44)
Caused by: org.hibernate.HibernateException: C:/MyApp/lib/hibernate.cfg.xml not found
at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1411)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1433)
at org.hibernate.cfg.AnnotationConfiguration.configure(AnnotationConfiguration.java:972)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:753)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:191)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:253)
... 10 more
ERROR MyDaoImpl - No EntityManager configured.
DEBUG MyDaoImpl - getTransaction() returns null
ERROR MyDaoImpl - No Transaction configured.
How can I access that external hibernate.cfg.xml from persistence.xml?
The error here is
Caused by: org.hibernate.HibernateException: C:/MyApp/lib/hibernate.cfg.xml not found
As it was pointed out in a comment, it looks for it in the folder WEB-INF/clases
Copy the file to that folder and change the following line to:
<property name="hibernate.ejb.cfgfile" value="hibernate.cfg.xml" />
Cheers.
I am using EclipseLink and even I have all necessary jar files imported with maven, I get still the Exception:
Exception in thread "main" javax.persistence.PersistenceException: No
resource files named
META-INF/services/javax.persistence.spi.PersistenceProvider were
found. Please make sure that the persistence provider jar file is in
your classpath.
In Maven pom I have the dependency:
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
<scope>provided</scope>
</dependency>
Here is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="PersistenzJPAProjekt">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.testJPABasis.Person</class>
</persistence-unit>
</persistence>
Here the clathpath in eclipse:
The class which actually generates the exception:
public class TestJPA
{
public static void main(String[] args)
{
Person person = new Person();
person.setPersonID(1);
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersistenzJPAProjekt");
EntityManager em = emf.createEntityManager();
}
}
The persistence.xml is directly under META-INF. As far as I know I don't need to have Glassfish or Tomcat as EclipseLink is made for standalone applications. If I am wrong maybe this is then the cause. The Meta-Inf is placed in:
persistence-api is just that: the API (mostly interfaces). You still need to include the actual persistence provider; it looks like you're wanting EclipseLink.