EJB/Hibernate does not access MySQL Database - mysql

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.

Related

MySQL + WildFly 10.0 - One or more services were unable to start

I'm trying to connect with database while deploying, but I got some trouble with that, here is a code and stacktrace:
02:19:32,740 ERROR [org.jboss.as.controller.management-operation] (ServerService Thread Pool -- 45) WFLYCTL0013: Operation ("add") failed - address: ([
("subsystem" => "datasources"),
("jdbc-driver" => "mysql")
]) - failure description: "WFLYJCA0041: Failed to load module for driver [org.mysql]"
02:19:32,814 INFO [org.wildfly.extension.undertow] (ServerService Thread Pool -- 55) WFLYUT0014: Creating file handler for path 'C:\Users \Damian\wildfly-10.0.0.Final/welcome-content' with options [directory-listing: 'false', follow-symlink: 'false', case-sensitive: 'true', safe-symlink-paths: '[]']
02:19:32,839 INFO [org.wildfly.extension.undertow] (MSC service thread 1-2) WFLYUT0012: Started server default-server.
02:19:32,840 INFO [org.wildfly.extension.undertow] (MSC service thread 1-2) WFLYUT0018: Host default-host starting
02:19:32,925 INFO [org.jboss.as.ejb3] (MSC service thread 1-5) WFLYEJB0481: Strict pool slsb-strict-max-pool is using a max instance size of 64 (per class), which is derived from thread worker pool sizing.
02:19:32,925 INFO [org.jboss.as.ejb3] (MSC service thread 1-2) WFLYEJB0482: Strict pool mdb-strict-max-pool is using a max instance size of 16 (per class), which is derived from the number of CPUs on this host.
02:19:33,157 INFO [org.jboss.as.server.deployment] (MSC service thread 1-5) WFLYSRV0027: Starting deployment of "FiranyCRM.war" (runtime-name: "FiranyCRM.war")
02:19:33,171 INFO [org.jboss.as.server.deployment] (MSC service thread 1-6) WFLYSRV0027: Starting deployment of "mysql-connector-java-5.1.37.jar" (runtime-name: "mysql-connector-java-5.1.37.jar")
02:19:33,186 INFO [org.jboss.as.server.deployment.scanner] (MSC service thread 1-5) WFLYDS0013: Started FileSystemDeploymentService for directory C:\Users\Damian\wildfly-10.0.0.Final\standalone\deployments
02:19:33,232 INFO [org.infinispan.factories.GlobalComponentRegistry] (MSC service thread 1-6) ISPN000128: Infinispan version: Infinispan 'Mahou' 8.1.0.Final
02:19:33,506 INFO [org.wildfly.extension.undertow] (MSC service thread 1-8) WFLYUT0006: Undertow HTTP listener default listening on 127.0.0.1:8080
02:19:33,771 INFO [org.jboss.ws.common.management] (MSC service thread 1-8) JBWS022052: Starting JBossWS 5.1.3.Final (Apache CXF 3.1.4)
02:19:33,827 INFO [org.jboss.as.jpa] (MSC service thread 1-8) WFLYJPA0002: Read persistence.xml for firanyDS
02:19:33,880 INFO [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-3) WFLYJCA0005: Deploying non-JDBC-compliant driver class com.mysql.jdbc.Driver (version 5.1)
02:19:33,882 INFO [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-3) WFLYJCA0005: Deploying non-JDBC-compliant driver class com.mysql.fabric.jdbc.FabricMySQLDriver (version 5.1)
02:19:33,916 INFO [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-3) WFLYJCA0018: Started Driver service with driver-name = mysql-connector-java-5.1.37.jar_com.mysql.jdbc.Driver_5_1
02:19:33,917 INFO [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-3) WFLYJCA0018: Started Driver service with driver-name = mysql-connector-java-5.1.37.jar_com.mysql.fabric.jdbc.FabricMySQLDriver_5_1
02:19:34,213 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "FiranyCRM.war")]) - failure description: {
"WFLYCTL0180: Services with missing/unavailable dependencies" => [
"jboss.persistenceunit.\"FiranyCRM.war#firanyDS\".__FIRST_PHASE__ is missing [jboss.naming.context.java.jdbc.firanyDS]",
"jboss.persistenceunit.\"FiranyCRM.war#firanyDS\" is missing [jboss.naming.context.java.jdbc.firanyDS]"
],
"WFLYCTL0288: One or more services were unable to start due to one or more indirect dependencies not being available." => {
"Services that were unable to start:" => [
"jboss.deployment.unit.\"FiranyCRM.war\".component.\"com.sun.faces.config.ConfigureListener\".START",
"jboss.deployment.unit.\"FiranyCRM.war\".component.\"javax.faces.webapp.FacesServlet\".START",
"jboss.deployment.unit.\"FiranyCRM.war\".component.\"javax.faces.webapp.FacetTag\".START",
"jboss.deployment.unit.\"FiranyCRM.war\".component.\"javax.servlet.jsp.jstl.tlv.PermittedTaglibsTLV\".START",
"jboss.deployment.unit.\"FiranyCRM.war\".component.\"javax.servlet.jsp.jstl.tlv.ScriptFreeTLV\".START",
"jboss.deployment.unit.\"FiranyCRM.war\".component.\"managed-bean.com.firanycrm.controller.CurtainBean\".START",
"jboss.deployment.unit.\"FiranyCRM.war\".component.\"managed-bean.com.firanycrm.controller.LoginBean\".START",
"jboss.deployment.unit.\"FiranyCRM.war\".deploymentCompleteService",
"jboss.deployment.unit.\"FiranyCRM.war\".jndiDependencyService",
"jboss.naming.context.java.module.FiranyCRM.FiranyCRM.DefaultDataSource",
"jboss.undertow.deployment.default-server.default-host./FiranyCRM",
"jboss.undertow.deployment.default-server.default-host./FiranyCRM.UndertowDeploymentInfoService"
],
"Services that may be the cause:" => [
"jboss.jdbc-driver.mysql",
"jboss.naming.context.java.jdbc.firanyDS"
]
}
}
02:19:34,214 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([
("subsystem" => "datasources"),
("data-source" => "firanyDS")
]) - failure description: {"WFLYCTL0180: Services with missing/unavailable dependencies" => [
"org.wildfly.data-source.firanyDS is missing [jboss.jdbc-driver.mysql]",
"jboss.driver-demander.java:jboss/datasources/firanyDS is missing [jboss.jdbc-driver.mysql]"
]}
02:19:34,216 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([
("subsystem" => "datasources"),
("data-source" => "firanyDS")
]) - failure description: {
"WFLYCTL0180: Services with missing/unavailable dependencies" => [
"org.wildfly.data-source.firanyDS is missing [jboss.jdbc- driver.mysql]",
"jboss.driver-demander.java:jboss/datasources/firanyDS is missing [jboss.jdbc-driver.mysql]",
"org.wildfly.data-source.firanyDS is missing [jboss.jdbc- driver.mysql]"
],
"WFLYCTL0288: One or more services were unable to start due to one or more indirect dependencies not being available." => {
"Services that were unable to start:" => [
"jboss.data-source.reference-factory.firanyDS",
"jboss.naming.context.java.jboss.datasources.firanyDS"
],
"Services that may be the cause:" => [
"jboss.jdbc-driver.mysql",
"jboss.naming.context.java.jdbc.firanyDS"
]
}
}
standalone.xml:
<subsystem xmlns="urn:jboss:domain:datasources:4.0">
<datasources>
<datasource jndi-name="java:jboss/datasources/firanyDS" pool-name="firanyDS">
<connection-url>jdbc:mysql://127.0.0.1:3307/firanycrm</connection-url>
<driver>mysql</driver>
<pool>
<min-pool-size>10</min-pool-size>
<max-pool-size>20</max-pool-size>
<prefill>true</prefill>
</pool>
<security>
<user-name>root</user-name>
<password>root</password>
</security>
</datasource>
<drivers>
<driver name="mysql" module="org.mysql">
<xa-datasource-class>com.mysql.jdbc.Driver</xa-datasource-class>
</driver>
</drivers>
</datasources>
</subsystem>
module.xml (in modules folder, modules/org/mysql) :
<module xmlns="urn:jboss:module:1.0" name="org.mysql.driver">
<resources>
<resource-root path="mysql-connector-java-5.1.37.jar"/>
</resources>
<dependencies>
<module name="javax.api"/>
<module name="javax.transaction.api"/>
</dependencies>
</module>
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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="firanyDS" transaction-type="RESOURCE_LOCAL">
<jta-data-source>java:/jdbc/firanyDS</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
</properties>
</persistence-unit>
</persistence>
In which place I made a mistake?
You have at least two problems:
In the standalone.xml, under the datasources subsystem, you set the driver module to "org.mysql" but the module name in the module.xml is "org.mysql.driver".
The jta-data-source element in persistence.xml should be the jndi name of your datasource: java:jboss/datasources/firanyDS. Besides, since you are using JTA, the transaction-type must be "JTA".
<persistence ...>
<persistence-unit name="firanyDS" transaction-type="JTA">
<jta-data-source>java:/jdbc/firanyDS</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
</properties>
</persistence-unit>
</persistence>

Rollback in MyBatis using JDBC (no Spring, no containers)

I've seen all sorts of posts on using Spring and MyBatis with transactions, but I'm facing a problem with rollbacks not working with plain old JDBC.
My ( test / throwaway) code is pretty simple : I open a session, insert a rec, throw an error on purpose and rollback the transaction. However, it always commits.
public static void main (String[] args){
//-- omitted for brevity
try {
org.apache.ibatis.logging.LogFactory.useSlf4jLogging();
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sess = sqlSessionFactory.openSession(false);
BillsMapper mapper = sess.getMapper(BillsMapper.class);
BillState billState = new BillState();
billState.setBillId(-1);
billState.setLastName("TESTER");
billState.setFirstName("TESTER");
mapper.insert(billState);
logger.info("Post insert: key = {}", billState.getBillId());
if(1 == 1)
throw new RuntimeException("Error Thrown on purpose...testing rollback ");
sess.commit();
}catch(Exception e){
logger.error("Error: {}", e);
sess.rollback();
}finally{
sess.close();
logger.info("Finito!");
}
}
The logs show:
DEBUG | (BaseJdbcLogger.java:145) - ==> Preparing: insert into bills (users_userId, refId, firstName, ...
DEBUG | (BaseJdbcLogger.java:145) - ==> Parameters: 67(Integer), 67-120530180328(String), TESTER(String), ...
DEBUG | (BaseJdbcLogger.java:145) - <== Updates: 1
INFO | (TestAction.java:50) - Post insert: key = 2478
ERROR | (TestAction.java:56) - Error: {} java.lang.RuntimeException: Error Thrown on purpose...testing rollback at com.s2stest.TestAction.main(TestAction.java:53)
DEBUG | (JdbcTransaction.java:79) - Rolling back JDBC Connection [com.mysql.jdbc.JDBC4Connection#371e88fb]
DEBUG | (JdbcTransaction.java:122) - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection#371e88fb]
DEBUG | (JdbcTransaction.java:90) - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection#371e88fb]
DEBUG | (PooledDataSource.java:344) - Returned connection 924748027 to pool.
Note the resetting of autocommit before closing the connection.... Would resetting autcommit before closing the SqlSession cause my rolled-back transaction to be committed? If so, is this a bug? Has anyone gotten JDBC working with transactions? I need it for testing, and I'd value some help. Right now, no transactions can be rolled back.
I've looked at the MyBatis source, and it indeed calls resetAutocommit before closing the connection. I'm using MySQL 5.6 and mysql-connector-java-5.1.36.jar for the driver if someone has a workaround that they've found.
--- UPDATE ---
mybatis-config.xml is as follows:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="SLF4J" />
</settings>
<typeAliases>
<package name="com.ship2storage.domain" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mytestDb?zeroDateTimeBehavior=convertToNull" />
<property name="username" value="--shhh!!--" />
<property name="password" value="--shhh!!--" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/ship2storage/db/maps/BillsMapper.xml" />
</mappers>
</configuration>
OK, I've found the answer by digging deeper into my setup. It seems that the MySQL storage engine I installed for my test DB is ISAM. ISAM does not support transactions. I switched to InnoDB using the following SQL tidbit, and transactions now work with JDBC:
ALTER TABLE bills ENGINE=InnoDB;
I haven't tried this, but it looks like you can also do this temporarily too:
SET default_storage_engine=InnoDB;
Hopefully this will help someone. The code/config posted above works.

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;
...
}

JPA + MySQL: After Timeout --> use a local Connection

as our connection is very unstable we have decided to switch to our local read-only database if a query times out.
But here is my problem: I do not get an exception when javax.persistence tries to query:
// Attribute
EntityManagerFactory entityManagerFactory;
EntityManager manager;
entityManagerFactory = Persistence
.createEntityManagerFactory("org.hibernate.tutorial.jpa");
manager = entityManagerFactory.createEntityManager();
try {
Query query = manager.createQuery(String.format(
"SELECT u FROM User u WHERE u.id = '%s'", 116));
User user = (User) query.getSingleResult();
manager.refresh(user);
System.out.println(user.getUsername());
} catch (org.hibernate.QueryTimeoutException ex) {
throw new QueryTimeoutException("timeout");
}
}
This is just a test to demonstrate my problem.
What am I missing?
Mysql: mysql-connector-java-5.1.16-bin.jar
JPA: javax.persistence_2.0.3.v201010191057.jar
Hibernate:
115 [main] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
124 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.6.7.Final
126 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found
129 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
132 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
208 [main] INFO org.hibernate.ejb.Version - Hibernate EntityManager 3.6.7.Final
persistence.xml:
<properties>
<property name="hibernate.hbm2ddl.auto" value="valide"/>
<property name="hibernate.connection.url" value="jdbc:mysql:///database?zeroDateTimeBehavior=convertToNull"/>
<property name="hibernate.connection.username" value="user"/>
<property name="hibernate.connection.password" value="pass"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.query.timeout" value="1"/>
<property name="dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
Thank you
Tobias
Solution:
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://server/database", "user", "pass");
Every time I want to start a query I test if the Connection is alive:
if (connection.isValid(1)) {
return true;
} else {
throw new NoConnectionException();
You may not be seeing a timeout because some DBs don't support that feature.
"javax.persistence.query.timeout query timeout in milliseconds
(Integer or String), this is a hint used by Hibernate but requires
support by your underlying database."
See http://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html/configuration.html for more details.
I'd be inclined to switch to the read only all the time if you can't guarantee a reliable connection.

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