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

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.

Related

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.

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

hibernate closing connections or not?

My code is below. Possibly I am using it many times in similar manner, i.e in simple words, I am managing the session and transaction this way:
List<Login> users= null;
try{
session=HibernateUtil.getSessionFactory().getCurrentSession();
tx=session.beginTransaction();
users=session.createQuery("from Login").list();
tx.commit();
}catch(Exception e){System.out.println("commit exception:"+e);
try {tx.rollback();} catch (Exception ex) {System.out.println("rollback exception:"+ex);}
}finally{if(session!=null && session.isOpen()){session.close();}}
return users;
Now, when I first run the database service(using MySQL) and check from command prompt using this query ...
show status like 'Conn%';
... the result is:
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Connections | 2 |
+---------------+-------+
When I start my application and use it. After opening few pages and querying the same thing. I am getting the connections as 6, I have even seen above 20.
Now I would like to know that hibernate is closing the connections or not?
I am handling all the transactions that way, I cross checked and dint see any code block without closing the session.
Hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/shareapp
</property>
<property name="connection.username">pluto</property>
<property name="connection.password">admin</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
</session-factory>
hibernateutil class
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Login.class);
config.addAnnotatedClass(FilesInfo.class);
config.addAnnotatedClass(FilesShare.class);
config.configure("hibernate.cfg.xml");
// new SchemaExport(config).create(true,true);
sessionFactory = config.buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Thanks!
The "Connections" status variable just refers to the
The number of connection attempts (successful or not) to the MySQL server,
and not the number of active connections.
Here is the link: http://dev.mysql.com/doc/refman/5.1/en/server-status-variables.html#statvar_Connections
To get the number of open connections, check the 'Threads_connected' variable, documented at
http://dev.mysql.com/doc/refman/5.1/en/server-status-variables.html#statvar_Threads_connected

Having connection issue Hibernate 3.0 with MySQL

I am getting this error. I have my hibernate connections and MVC all setup correct I believe.
I heard MySQL drivers have an issue for database connection.
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/AdministrativeApplication] threw exception [Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection] with root cause
java.sql.SQLException: Unknown database 'testDB'
My hibernate configuration file
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!-- Load Hibernate related configuration -->
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/testDB" />
<property name="username" value="myroot"/>
<property name="password" value="*****"/>
<!-- connection pooling details -->
<property name="initialSize" value="1"/>
<property name="maxActive" value="5"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<!-- Declare a transaction manager-->
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<!-- all the annotation entity classes -->
</list>
</property>
</bean>
<!-- Declare a transaction manager-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
</beans>
Please let me know what
I could do to resolve this error.
I further added a new java file to test
import java.sql.*;
public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String userName = "root";
String password = "******";
String url = "jdbc:mysql://localhost:3306/testDB";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
e.printStackTrace(System.out);
System.err.println ("Cannot connect to database server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
I get this error . Also I started the MySQL console with this command.
"C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld.exe"
I get this error
java.sql.SQLException: Unknown database 'testdb'
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2975)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:798)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3700)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1203)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2572)
at com.mysql.jdbc.Connection.<init>(Connection.java:1485)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at Connect.main(Connect.java:15)
Cannot connect to database server
Can some please help resolve this.
i ran netstats no luck. I do not see at what port MySQL is listening at.
Thanks again .
Dhiren
I am getting this error.
This means you did something wrong.
I have my hibernate connections and MVC all setup correct I believe.
See my previous comment - you did not do everything correctly.
I heard MySQL drivers have an issue for database connection.
Nope - MySQL drivers work fine if you set them up properly. You're doing something wrong, and you'll make progress faster if you take that attitude.
Before you run Java, start up the MySQL client, log into MySQL. If you can't, Java won't be able to, either. See if the daemon is up and running.
See if you have that database available. If not, create it.
If it is created, make sure that you have the tables you need and the user you're logging in as has appropriate permissions.
You could create a database named "testDB" in your MySQL instance.