Playframework Hibernate JPA cannot connect to Database - mysql

I'm trying to configure Hibernate JPA to access database. Without using Hibernate JPA, It accesses to database well, but when using Hibernate JPA it does not.
I'm following this tutorial:
https://www.playframework.com/documentation/2.5.x/JavaJPA
These are my steps:
build.sbt
//Hibernate JPA
libraryDependencies ++= Seq( javaJpa, "org.hibernate" % "hibernate-entitymanager" % "5.1.0.Final" // replace by your jpa implementation )
//JPA
PlayKeys.externalizeResources := false
//Driver for mysql
libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.36"
conf/application.conf
db {
# You can declare as many datasources as you want.
# By convention, the default datasource is named `default`
default.driver = "com.mysql.jdbc.Driver"
default.url = "jdbc:mysql://localhost:3306/sakila"
default.username = root
default.password = "root"
default.jndiName=DefaultDS
jpa.default=defaultPersistenceUnit
default.logSql=true
}
conf/META_INF/persistence.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="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<non-jta-data-source>DefaultDS</non-jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
</properties>
</persistence-unit>
</persistence>
Error messages:
! #70fdppp3i - Internal server error, for (GET) [/count] ->
play.api.Configuration$$anon$1: Configuration error[Cannot connect to database [jpa]]
at play.api.Configuration$.configError(Configuration.scala:154)
at play.api.Configuration.reportError(Configuration.scala:806)
at play.api.db.DefaultDBApi$$anonfun$connect$1.apply(DefaultDBApi.scala:48)
at play.api.db.DefaultDBApi$$anonfun$connect$1.apply(DefaultDBApi.scala:42)
at scala.collection.immutable.List.foreach(List.scala:381)
at play.api.db.DefaultDBApi.connect(DefaultDBApi.scala:42)
at play.api.db.DBApiProvider.get$lzycompute(DBModule.scala:72)
at play.api.db.DBApiProvider.get(DBModule.scala:62)
at play.api.db.DBApiProvider.get(DBModule.scala:58)
at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:81)
Caused by: play.api.Configuration$$anon$1: Configuration error[either dataSource or dataSourceClassName is required]
at play.api.Configuration$.configError(Configuration.scala:154)
at play.api.PlayConfig.reportError(Configuration.scala:996)
at play.api.db.HikariCPConnectionPool.create(HikariCPModule.scala:70)
at play.api.db.PooledDatabase.createDataSource(Databases.scala:199)
at play.api.db.DefaultDatabase.dataSource$lzycompute(Databases.scala:123)
at play.api.db.DefaultDatabase.dataSource(Databases.scala:121)
at play.api.db.DefaultDatabase.getConnection(Databases.scala:142)
at play.api.db.DefaultDatabase.getConnection(Databases.scala:138)
at play.api.db.DefaultDBApi$$anonfun$connect$1.apply(DefaultDBApi.scala:44)
at play.api.db.DefaultDBApi$$anonfun$connect$1.apply(DefaultDBApi.scala:42)
Caused by: java.lang.IllegalArgumentException: either dataSource or dataSourceClassName is required
at com.zaxxer.hikari.HikariConfig.validate(HikariConfig.java:785)
at play.api.db.HikariCPConfig.toHikariConfig(HikariCPModule.scala:141)
at play.api.db.HikariCPConnectionPool$$anonfun$1.apply(HikariCPModule.scala:57)
at play.api.db.HikariCPConnectionPool$$anonfun$1.apply(HikariCPModule.scala:54)
at scala.util.Try$.apply(Try.scala:192)
at play.api.db.HikariCPConnectionPool.create(HikariCPModule.scala:54)
at play.api.db.PooledDatabase.createDataSource(Databases.scala:199)
at play.api.db.DefaultDatabase.dataSource$lzycompute(Databases.scala:123)
at play.api.db.DefaultDatabase.dataSource(Databases.scala:121)
at play.api.db.DefaultDatabase.getConnection(Databases.scala:142)
Error message on screen:
How to solve it?
I'm using Play framework 2.5

I think your jpa.default property is in wrong place. Try like this:
db {
# You can declare as many datasources as you want.
# By convention, the default datasource is named `default`
default.driver = "com.mysql.jdbc.Driver"
default.url = "jdbc:mysql://localhost:3306/sakila"
default.username = root
default.password = "root"
default.jndiName=DefaultDS
default.logSql=true
}
jpa.default=defaultPersistenceUnit

Related

How configure TomEE and JPA

sorry for my bad english, (Im french :-D).
I want work with TomEE for JPA, but my configuration is bad i think.
I receive a exception when i try to connecte to my database (Mysql).
persistence.xml
<persistence-unit name="elevage" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>elevage</jta-data-source>
<non-jta-data-source>elevageUnmanaged</non-jta-data-source>
<class>com.test.ejb.BeanAnimal</class>
<properties>
<property name="openjpa.jdbc.DBDictionary" value="mysql" />
<property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO" />
</properties>
</persistence-unit>
tomee.xml
<Resource id="elevage" type="DataSource">
JdbcDriver com.mysql.jdbc.Driver
JdbcUrl jdbc:mysql://localhost:3306/elevage2?useLegacyDatetimeCode=false&serverTimezone=Australia/Sydney&useSSL=false
UserName root
Password pass
JtaManaged true
DefaultAutoCommit false
</Resource>
<Resource id="elevageUnmanaged" type="DataSource">
JdbcDriver com.mysql.jdbc.Driver
JdbcUrl jdbc:mysql://localhost:3306/elevage2?useLegacyDatetimeCode=false&serverTimezone=Australia/Sydney&useSSL=false
UserName root
Password pass
JtaManaged false
</Resource>
Exception
AVERTISSEMENT: Unexpected exception from beforeCompletion; transaction will roll back
<openjpa-2.4.1-r422266:1730418 fatal general error> org.apache.openjpa.persistence.PersistenceException: user lacks privilege or object not found: OPENJPA_SEQUENCE_TABLE {SELECT SEQUENCE_VALUE FROM OPENJPA_SEQUENCE_TABLE WHERE ID = ? FOR UPDATE} [code=-5501, state=42501]
Request is a "SELECT" and i want take all data in my database. I have see documentation but the problem persiste.
Thank all for your answer !
(if you need more file, tell me :-) )
After a long time tearing my hair, I found a solution, if it can save time, here it is:
2 Configurations!
In development:
tomee.xml is not used, it is necessary to configure openejb.xml whose path is specified in the eclipse console, attention, the access is by hidden file
Path for my machine (Linux):
/home/user/eclipse-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp2/conf/openejb.xml
At the bottom of the file, you have section "Resource", the configuration is identical to tomee.xml (you can find documentation at this adress : documentation for configuration tomee.xml
In production:
we forget openejb.xml, a configuration is identical but in tomee.xml
to finish, here is my configuration:
persistence.xml
<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="elevage" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>MyDataBase</jta-data-source>
<non-jta-data-source>MyDataBaseUnmanaged</non-jta-data-source>
<class>com.test.ejb.BeanAnimal</class>
<!-- <class>com.test.ejb.BeanUser</class>-->
<properties>
<property name="openjpa.jdbc.DBDictionary" value="mysql" />
<property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO" />
</properties>
</persistence-unit>
openejb.xml (in development) and tomee.xml (in production)
<Resource id="MyDataBase" type="DataSource">
JdbcDriver com.mysql.jdbc.Driver
JdbcUrl jdbc:mysql://localhost:3306/elevage?useLegacyDatetimeCode=false&serverTimezone=Australia/Sydney&useSSL=false
UserName root
Password pass
JtaManaged true
</Resource>
<Resource id="MyDataBaseUnmanaged" type="DataSource">
JdbcDriver com.mysql.jdbc.Driver
JdbcUrl jdbc:mysql://localhost:3306/elevage?useLegacyDatetimeCode=false&serverTimezone=Australia/Sydney&useSSL=false
UserName root
Password pass
JtaManaged false
</Resource>

EJB/Hibernate does not access MySQL Database

I'm trying to learn how to work with JavaEE/EJB and database persistence, I have a basic example where I want to save a String to a database via input field and read the list of saved items.
I have a MySQL server installed on localhost (V5.7 Community Edition) and my test server is WildFly 10.1.0 (via Eclipse). The whole project is an EAR container containing a Web and EJB Subproject.
I am using container managed transactions, as I understand it, transactions are automatically created when a method is called and flushed/committed as soon as the method exits.
The problem is, that no data is ever written to the actual database. But no errors are thrown either. I assume, the entity manager caches all supposed saves and directly reads them back on select, without even checking the database. As such, when I restart the server, nothing remains. Also, when I look into mysql db directly, nothing is there either (even while wildfly server is running, directly after supposed insert). I also tried adding some rows to db table directly, but select does not "see" them either.
As a result, it seemed to me that the database is not even accessed, despite it being configured in the persistence.xml. I tried to remove connection url/username/password there and it actually made no difference, the entity manager still throws no errors and everything seems to work. So where exactly is it saving the data and what do I have to change so that it accesses the supplied mysql database instead?
Handler (in Web Project):
#ManagedBean(name = "handlerBean")
#SessionScoped
public class HandlerBean {
#EJB
private TodoWorkerBeanRemote worker;
private String input;
public void add() {
if (input.compareTo("") != 0) {
TodoBean item = new TodoBean();
item.setText(input);
worker.saveItem(item);
input = "";
}
}
...
Session Bean / Transaction container (in EJB project)
#Stateless
#TransactionManagement(TransactionManagementType.CONTAINER)
public class TodoWorkerBean implements TodoWorkerBeanRemote {
#PersistenceContext(unitName = "EnterpriseTestEJB")
private EntityManager entityManager;
public TodoWorkerBean() {
}
#Override
#TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) // does not help
public void saveItem(TodoBean item) {
// entityManager.joinTransaction(); <- does not help
entityManager.persist(item); // tried .merge() as well
// entityManager.flush(); <-does not help
}
...
Entity Bean (in EJB project)
#Entity
#Table(name = "todobean")
#NamedNativeQueries({
#NamedNativeQuery(name = "TodoBean.getItems", query = "select * from todobean", resultClass = TodoBean.class),
#NamedNativeQuery(name = "TodoBean.clearItems", query = "delete from todobean") })
public class TodoBean implements Serializable {
private Integer id;
private String text;
...
persistence.xml (tried with hibernate.cfg.xml as well, no difference)
<?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="EnterpriseTestEJB">
<class>de.dianasalsa.ejb.TodoBean</class>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/feedback" /> // not used
<property name="hibernate.connection.username" value="root" /> // not used
<property name="hibernate.connection.password" value="root" /> // not used
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.use_sql_comments" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.hbm2ddl.auto" value="update" /> // tried "create" as well
</properties>
</persistence-unit>
</persistence>
Log:
....
15:42:59,602 INFO [org.jboss.as.jpa] (ServerService Thread Pool -- 66) WFLYJPA0010: Starting Persistence Unit (phase 2 of 2) Service 'EnterpriseTest.ear/EnterpriseTestEJB.jar#EnterpriseTestEJB'
15:42:59,952 INFO [org.jboss.as.clustering.infinispan] (ServerService Thread Pool -- 65) WFLYCLINF0002: Started client-mappings cache from ejb container
15:42:59,973 INFO [org.hibernate.dialect.Dialect] (ServerService Thread Pool -- 66) HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
15:43:00,102 INFO [org.hibernate.envers.boot.internal.EnversServiceImpl] (ServerService Thread Pool -- 66) Envers integration enabled? : true
15:43:00,101 INFO [org.jboss.as.protocol] (management I/O-1) WFLYPRT0057: cancelled task by interrupting thread Thread[management-handler-thread - 3,5,management-handler-thread]
15:43:00,604 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (ServerService Thread Pool -- 66) HHH000228: Running hbm2ddl schema update
15:43:00,617 INFO [org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl] (ServerService Thread Pool -- 66) HHH000262: Table not found: todobean
15:43:00,619 INFO [org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl] (ServerService Thread Pool -- 66) HHH000262: Table not found: todobean
15:43:01,499 INFO [javax.enterprise.resource.webcontainer.jsf.config] (ServerService Thread Pool -- 83) Mojarra 2.2.13.SP1 20160303-1204 für Kontext '/EnterpriseTestWeb' wird initialisiert.
15:43:02,379 INFO [org.wildfly.extension.undertow] (ServerService Thread Pool -- 83) WFLYUT0021: Registered web context: /EnterpriseTestWeb
15:43:02,414 INFO [org.jboss.as.server] (ServerService Thread Pool -- 34) WFLYSRV0010: Deployed "EnterpriseTest.ear" (runtime-name : "EnterpriseTest.ear")
15:43:02,515 INFO [org.jboss.as] (Controller Boot Thread) WFLYSRV0060: Http management interface listening on http://127.0.0.1:9990/management
15:43:02,519 INFO [org.jboss.as] (Controller Boot Thread) WFLYSRV0051: Admin console listening on http://127.0.0.1:9990
15:43:02,519 INFO [org.jboss.as] (Controller Boot Thread) WFLYSRV0025: WildFly Full 10.1.0.Final (WildFly Core 2.2.0.Final) started in 9581ms - Started 879 of 1127 services (422 services are lazy, passive or on-demand)
15:43:18,799 INFO [org.jboss.ejb.client] (default task-2) JBoss EJB Client version 2.1.4.Final
15:43:32,763 INFO [stdout] (default task-3) Hibernate:
15:43:32,763 INFO [stdout] (default task-3) /* insert de.dianasalsa.ejb.TodoBean
15:43:32,763 INFO [stdout] (default task-3) */ insert
15:43:32,763 INFO [stdout] (default task-3) into
15:43:32,763 INFO [stdout] (default task-3) todobean
15:43:32,763 INFO [stdout] (default task-3) (text)
15:43:32,763 INFO [stdout] (default task-3) values
15:43:32,764 INFO [stdout] (default task-3) (?)
15:43:32,786 INFO [stdout] (default task-3) Hibernate:
15:43:32,786 INFO [stdout] (default task-3) /* TodoBean.getItems */ select
15:43:32,786 INFO [stdout] (default task-3) *
15:43:32,787 INFO [stdout] (default task-3) from
15:43:32,787 INFO [stdout] (default task-3) todobean
sorry for my english...
you need to configure a JNDI name "jta-data-source", and say with "hibernate.hbm2ddl.auto" create new relations, like this example:
<?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="EnterpriseTestEJB"
transaction-type="JTA">
<jta-data-source>java:jboss/datasources/some-name</jta-data-source>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
wildfly has a "namesever" for that you work with the JNDI name to access from your annotation like "#PersistenceContext".
And in Wildfly at selfe you must configure a new MySql connection with that JNDI name.
For MySql connection download the jdbc driver and upload it to WildFly.
https://dev.mysql.com/downloads/connector/j/5.1.html
Inser MySqgl jdbc Driver
The connection will named with the JNDI name (java:jboss/datasources/some-name).
Add new MySql Connection (1)
Add new MySql Connection (2)
When you run your programm in Wildfly the programm will look over the JNDI name in wildfly for your MySql connection.
If you would like to look an example code i have one from my study here:
https://gitlab.com/Java_Project/JavaEE2.0
I'll hope it fixe your problem.

Jetty configuration: problems with MySQL JNDI

The Jetty embedded has a jetty.xml for the configuration. This configuration has a mysql jndi-connection.
When I run jetty with gradle, it throws an exception:
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource
at org.eclipse.jetty.util.Loader.loadClass(Loader.java:86)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.nodeClass(XmlConfiguration.java:364)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.newObj(XmlConfiguration.java:754)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.itemValue(XmlConfiguration.java:1125)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.value(XmlConfiguration.java:1030)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.newObj(XmlConfiguration.java:775)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.configure(XmlConfiguration.java:423)
at org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration.configure(XmlConfiguration.java:298)
at org.eclipse.jetty.xml.XmlConfiguration.configure(XmlConfiguration.java:248)
at org.eclipse.jetty.xml.XmlConfiguration$configure.call(Unknown Source)
at com.sahlbach.gradle.plugins.jettyEclipse.JettyEclipseRun.applyJettyXml(JettyEclipseRun.groovy:533)
at com.sahlbach.gradle.plugins.jettyEclipse.JettyEclipseRun.startJetty(JettyEclipseRun.groovy:318)
This is the line of jetty.xml where the exception is thrown:
<New id="relevante" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg></Arg>
<Arg>jdbc/Relevante</Arg>
<Arg>
<New id="relevanteDataSource" class="com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource">
<Set name="url">jdbc:mysql://localhost:3306/xxxx</Set>
<Set name="user">xxxx</Set>
<Set name="password">xxxx</Set>
</New>
</Arg>
</New>
The MySQL connector is a dependency of gradle and I don't know if I need to place the connector into a local address (in addition to as dependency in gradle).
jettyEclipse {
additionalRuntimeJars = files( new File("$rootDir/src/main/webapp/WEB-INF/lib/mysql-connector-java-5.0.8-bin.jar") )
warFile = file("$rootDir/build/libs/relevanteme.war")
jettyConfig = file("$rootDir/jetty.xml")
contextPath = ""
automaticReload = "true"
scanIntervalInSeconds = 5
webDefaultXml = file("$rootDir/webdefault.xml")
}
Thanks!!
What's the task to run jetty? Do you know if there is a separate configuration for that and does it extends from compile?
The solution's to have two xml files for server configuration. One of these two files will be jetty.xml which will have all the server configuration. The other file will be jetty-env.xml with webApp configuration and connection to the database (this file has to be in webapp/WEB-INF/).
More information in this repository.

javax.persistence.PersistenceException: Unable to build entity manager factory

When I'm trying to create a new EntityManager to persist my data, i get the following Error:
javax.persistence.PersistenceException: Unable to build entity manager factory
I using the JPA-Persistence Provider of Hibernate...
unluckily I couldn't find any helpful post in stackoverflow / with googling...
Does anybody have an idea where the cause of the error could lie?
Thank you for your help!
code-snippets:
creation of entitymanager
EntityManager em;
EntityManagerFactory fact = Persistence.createEntityManagerFactory("bachelordebug"); // Here it crashes
em = fact.createEntityManager();
stacktrace
javax.persistence.PersistenceException: Unable to build entity manager factory
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:81)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:54)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at com.uzh.platform.api.util.AssignmentUtil.findAll(AssignmentUtil.java:20)
at com.uzh.platform.api.services.GetAssignments.getAssignments(GetAssignments.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:151)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:171)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:152)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:402)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:349)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:106)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:259)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:318)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:236)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1010)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:373)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:382)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:345)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:220)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1221)
at com.thetransactioncompany.cors.CORSFilter.doFilter(CORSFilter.java:156)
at com.thetransactioncompany.cors.CORSFilter.doFilter(CORSFilter.java:233)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1212)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:399)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:766)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:450)
at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:230)
at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:928)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:549)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:410)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
persistence.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="bachelordebug" transaction-type="RESOURCE_LOCAL">
<!-- <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> -->
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.uzh.platform.data.dao.Assignment</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://127.0.0.1:5432/bachelor"/>
<property name="javax.persistence.jdbc.user" value="bachelor"/>
<property name="javax.persistence.jdbc.password" value="bachelor14"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.release_mode" value="after_statement"/>
<property name="connection.pool_size" value="1"/>
<property name="dialect" value="org.postgresql.Driver"/>
<property name="current_session_context_class" value="thread"/>
<property name="cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="show_sql" value="true"/>
</properties>
</persistence-unit>
(Question answered in comments and edits. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:
SOLVED
I finally found my error!
In my JPA-Entity class, I misspelled my Named-Query Annotation (even though I don't use it)
#NamedQuery(name="Assignment.findAll", query ="SELECT * FROM assignment")
of course one has to write that in capital Letters, i.e. "Assignment" (i.e. all terms like they appear in the service-class!)
3 days wasted with this stupid error - but now I learned how to do it! :-)
Thanks anyway for your help!
Since the error can indicate a lot of different causes it seems best to get to the cause examining the Hibernate DEBUG log statements (we use logback, but it should work in any other logging framework similarly):
With this you get a lot of output, but can determine the actually interesting classes (it is very likely you will spot the cause here already):
// (logback.groovy)
logger( "org.hibernate", DEBUG )
Which for us showed something like the following (where Mapping collection: foo.Bar.field -> some_tab_x was the info we needed to spot the faulty mapping):
07:32:43.720 D~ [main ~ main] [ : ] CollectionSecondPass:SecondPass: 67|
Second pass for collection: foo.Bar.field
07:32:43.720 D~ [main ~ main] [ : ] c.a.CollectionBinder:SecondPass: 823|
Binding a OneToMany: foo.Bar.field through a foreign key
07:32:43.720 D~ [main ~ main] [ : ] c.a.CollectionBinder:SecondPass: 861|
Mapping collection: foo.Bar.field -> some_tab_x
07:32:43.727 D~ [main ~ main] [ : ] ePersistenceProvider:gerFactory: 82|
Unable to build entity manager factory
07:32:43.743 E~ [main ~ main] [ : ] .l.f.m.m.MgFooTstJu:AndRethrow: 74|
MyException: unit test error loading Foo with id: 4342153208-2:
<java.lang.NullPointerException> =>
<javax.persistence.PersistenceException: Unable to build entity manager factory>
To restrict the logging again (if there are multiple places to fix your JPA mapping), we then used something like the following:
// (logback.groovy)
//logger( "org.hibernate", DEBUG ) // log everything
// infos on annotation mappping, e.g. getting NullPointerExceptions with
// javax.persistence.PersistenceException: Unable to build entity manager factory
logger( "org.hibernate.cfg.annotations.CollectionBinder", DEBUG )
(E.g. in Eclipse just use CTRL+SHIFT+T to search for the type you like to debug, if the log output does not show the complete classname)
I encountered the same error, and unfortunately the above answer didn't help me a lot. So I looked to other errors reported in my case where I found this error:
com.mysql.cj.core.exceptions.InvalidConnectionAttributeException: The server time zone value 'EEST' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
I solved it as specified the this answer and it's comments, by replacing my connection url with : "jdbc:mysql://localhost:3306/db?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"
That solved all errors including the one noted in this question:
javax.persistence.PersistenceException: Unable to build entity manager factory
I hope this helps others coming across the same issue I faced.
add the id annotation in your entity class
#Entity
public class yourClass{
#Id
private Long id;
...
}

ArgumentException: JDBC Driver or DataSource class

I'm attempting create a simple web app with a MySQL backend. I'm able to deploy my .ear in Geronimo. However, when I submit my form to persist some stuff to the DB via OpenJPA I get the following error (below is my stacktrace):
Caused by: org.apache.openjpa.persistence.ArgumentException: A JDBC Driver or DataSource class name must be specified in the ConnectionDriverName property.
My Project is an Enterprise Application Project (AReyes) with a web module (AReyesAdminWeb) and an ejb module (AReyesEJB).
My persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">
<persistence-unit name="AReyesPersistUnit" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>AReyesMySql</jta-data-source>
<class>com.areyes.entity.Admin</class>
<properties>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema"/>
</properties>
</persistence-unit>
</persistence>
The file is located in AReyesEJB/ejbModule/META-INF
What I'm using
Geronimo 2.2.1 with Tomcat 6
MySQL 5.5.11
OpenJPA 1.2.2
Eclipse Indego Release
OS X 10.6.7
StackTrace
Caused by: org.apache.openejb.OpenEJBException: Error while creating bean com.areyes.session.AdminManager: Error invoking constructor: public com.areyes.session.AdminManager()
at org.apache.openejb.InjectionProcessor.construct(InjectionProcessor.java:120)
at org.apache.openejb.InjectionProcessor.createInstance(InjectionProcessor.java:83)
at org.apache.openejb.core.stateless.StatelessInstanceManager.ceateInstance(StatelessInstanceManager.java:204)
at org.apache.openejb.core.stateless.StatelessInstanceManager.getInstance(StatelessInstanceManager.java:165)
at org.apache.openejb.core.stateless.StatelessContainer.invoke(StatelessContainer.java:165)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler.businessMethod(EjbObjectProxyHandler.java:217)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler._invoke(EjbObjectProxyHandler.java:77)
at org.apache.openejb.core.ivm.BaseEjbProxyHandler.invoke(BaseEjbProxyHandler.java:282)
... 23 more
Caused by: org.apache.xbean.recipe.ConstructionException: Error invoking constructor: public com.areyes.session.AdminManager()
at org.apache.xbean.recipe.ReflectionUtil$ConstructorFactory.create(ReflectionUtil.java:962)
at org.apache.xbean.recipe.ObjectRecipe.internalCreate(ObjectRecipe.java:276)
at org.apache.xbean.recipe.AbstractRecipe.create(AbstractRecipe.java:96)
at org.apache.xbean.recipe.AbstractRecipe.create(AbstractRecipe.java:61)
at org.apache.openejb.InjectionProcessor.construct(InjectionProcessor.java:118)
... 30 more
Caused by: <openjpa-1.2.2-r422266:898935 fatal user error> org.apache.openjpa.persistence.ArgumentException: A JDBC Driver or DataSource class name must be specified in the ConnectionDriverName property.
at org.apache.openjpa.jdbc.schema.DataSourceFactory.newDataSource(DataSourceFactory.java:74)
at org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl.createConnectionFactory(JDBCConfigurationImpl.java:784)
at org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl.getDBDictionaryInstance(JDBCConfigurationImpl.java:561)
at org.apache.openjpa.jdbc.meta.MappingRepository.endConfiguration(MappingRepository.java:1344)
at org.apache.openjpa.lib.conf.Configurations.configureInstance(Configurations.java:505)
at org.apache.openjpa.lib.conf.Configurations.configureInstance(Configurations.java:430)
at org.apache.openjpa.lib.conf.PluginValue.instantiate(PluginValue.java:103)
at org.apache.openjpa.conf.MetaDataRepositoryValue.instantiate(MetaDataRepositoryValue.java:68)
at org.apache.openjpa.lib.conf.ObjectValue.instantiate(ObjectValue.java:83)
at org.apache.openjpa.conf.OpenJPAConfigurationImpl.newMetaDataRepositoryInstance(OpenJPAConfigurationImpl.java:863)
at org.apache.openjpa.conf.OpenJPAConfigurationImpl.getMetaDataRepositoryInstance(OpenJPAConfigurationImpl.java:854)
at org.apache.openjpa.kernel.AbstractBrokerFactory.makeReadOnly(AbstractBrokerFactory.java:638)
at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:183)
at org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:142)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:192)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:145)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:56)
at com.areyes.session.AdminManager.<init>(AdminManager.java:22)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at org.apache.xbean.recipe.ReflectionUtil$ConstructorFactory.create(ReflectionUtil.java:952)
... 34 more
com.areyes.session.AdminManager is a #Stateless bean that has been injected into a servlet in AReyesAdminWeb (with #EJB anno). Here's the constrcutor:
#Stateless
public class AdminManager implements AdminService {
private EntityManagerFactory fac;
private EntityManager em;
public AdminManager () {
fac = Persistence.createEntityManagerFactory("AReyesPersistUnit", System.getProperties());
em = fac.createEntityManager();
}
The behavior seem like my web app is unaware of my persistence.xml in my ejb app. I wonder if I bundled everything up correctly.
I added this to my application.xml:
<module>
<connector>tranql-connector-mysql-local-1.5.rar</connector>
</module>
Then I added this to my geronimo-application.xml:
<app:module>
<app:connector>tranql-connector-mysql-local-1.5.rar</app:connector>
<app:alt-dd>mysql-plan.xml</app:alt-dd>
</app:module>
In my EA Project (AReyes) I've added mysql-plan.xml in the same folder with my META-INF. Then I imported the tranql-connector-mysql-local-1.5.rar from my Geronimo folder.
It sounds like the web app cannot find persistence.xml on its class path. From reading this thread you could have the same problem. Try moving persistence.xml to the following location and see how you go...
WEB-INF/classes/META-INF/persistence.xml