Instead of using a local mySQL Database i created an external database with https://remotemysql.com/. The problem I am having is that I cant connect to the database.
This is my hibernate config file:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- SQL Dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Database Connection Settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://www.remotemysql.com:3306/oJv6mOSx3X</property>
<property name="hibernate.connection.username">34kjldxck</property>
<property name="hibernate.connection.password">mysecpw</property>
<property name="show_sql">true</property>
<!-- Specifying Session Context -->
<property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>
<!-- Mapping With Model Class Containing Annotations -->
<mapping class="com.jcg.hibernate.maven.User" />
</session-factory>
This is how I am trying to connect to the database:
public class AppMain {
static Session sessionObj;
static SessionFactory sessionFactoryObj;
private static SessionFactory buildSessionFactory() {
// Creating Configuration Instance & Passing Hibernate Configuration File
Configuration configObj = new Configuration();
configObj.configure("hibernate.cfg.xml");
// Since Hibernate Version 4.x, ServiceRegistry Is Being Used
ServiceRegistry serviceRegistryObj = new StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build();
// Creating Hibernate SessionFactory Instance
sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);
return sessionFactoryObj;
}
public static void main(String[] args) {
try {
sessionObj = buildSessionFactory().openSession();
} catch(Exception ex){
ex.printStackTrace();
}
}
}
This is the error I get:
org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:122)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:140)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:58)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:75)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:106)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
at com.jcg.hibernate.maven.AppMain.buildSessionFactory(AppMain.java:24)
at com.jcg.hibernate.maven.AppMain.main(AppMain.java:30)
Caused by: java.sql.SQLException: java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.ConnectionImpl.buildCollationMapping(ConnectionImpl.java:1041)
at com.mysql.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:3481)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2445)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2215)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:813)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:399)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:334)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:55)
... 14 more
Caused by: java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long
at com.mysql.jdbc.ConnectionImpl.buildCollationMapping(ConnectionImpl.java:992)
... 27 more
enter code here
Now I am guessing that the error is because of the connection url I guess. Whats strange that i get am Math exception(igInteger cannot be cast to java.lang.Long)
if you scroll down into the error, in the caused by section , I think you have a field in database of type BigInteger and it's mapped to Long class field, which cause a ClassCastException
Hope it helps
This type of error indicates error to connect to the database
(search the exception for results).
It is hard to say what is the reason.
It could be related to the version of the connector.jar.
I would check that but first. Also would check if you are able to connect to a local database from your hibernate framework.
Related
I'm creating a GAE project with Spring which will also use cloud SQL. While testing this app in local I'm pointing to my local MySQL environment but when I'll deploy it to GAE, it will point to cloud SQL instance. So I want to configure my driverName in datasource bean depending on environment. To this we generally use following in our java code
if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
// Load the class that provides the new "jdbc:google:mysql://" prefix.
Class.forName("com.mysql.jdbc.GoogleDriver");
url = "jdbc:google:mysql://<your-project-id>:<your-instance-name>/<your-database-name>?user=root";
} else {
// Local MySQL instance to use during development.
Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://127.0.0.1:3306/<your-database-name>?user=root";
}
Now I want to achieve the same in applicationcontext.xml using Spring Expression language. I haven't done this before and not able to achieve it. Please guide me. This is what I tried
<bean id="isDev" class="java.lang.Boolean">
<constructor-arg value="#{ systemProperties[environment.value] == SystemProperty.Environment.Value.Development ? true : false }" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="#{ isDev ? com.mysql.jdbc.Driver : com.mysql.jdbc.GoogleDriver }" />
.
.
.
But I'm getting exception, attaching a part of exception
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'feedbackFormController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.sandeepapplabs.custengage.services.FeedbackFormService com.sandeepapplabs.custengage.controllers.FeedbackFormController.feedbackFormService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'feedbackFormService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.sandeepapplabs.custengage.daos.FeedbackFormDAO com.sandeepapplabs.custengage.services.impl.FeedbackFormServiceImpl.feedbackFormDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'feedbackFormDAO' defined in ServletContext resource [/WEB-INF/custengage-servlet.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/custengage-servlet.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is java.lang.NullPointerException
I believe you need to quote the class names to make them literals...
... 'com.mysql.jdbc.Driver' ...
However it is easier to use Spring Profiles](http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/beans.html#beans-definition-profiles-xml) and enable the profile you want.
You can use Spring profiles to change concrete bean classes. Let's say you have 2 profiles: "prod" and "dev". Your bean methods should have #Profile annotation as below:
#Configuration
public class AppConfig {
...
#Bean
#Profile("prod")
public Object prodDataSource() {
return new ...
}
#Bean
#Profile("dev")
public Object getDataSource() throws Exception {
return new ...
}
}
If you are using Maven, you can select profile through pom.xml:
<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<spring.profile>dev</spring.profile>
</properties>
</profile>
<profile>
<id>prod</id>
<activation>
<activeByDefault>false</activeByDefault>
<property>
<name>prod</name>
</property>
</activation>
<properties>
<spring.profile>prod</spring.profile>
</properties>
</profile>
</profiles>
You can pass profile selection argument by -D like: mvn -Dprod clean compile test install
EDIT:
In application.properties following property selects profile:
spring.profiles.active=${spring.profile}
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;
...
}
I have problem with Hibernate (hibernate-core-4.1.9.Final.jar)
Case 1: Hibernate testing inside for loop. Everything went well.
for(int i = 0; i < 1500; i++){
UserDAO.getInstance.getById(1);
}
Case 2: Thread.sleep() inside loop. Resulting with exception after 1 minute.
for(int i=0; i<1500; i++){
UserDAO.getInstance.getById(1);
Thread.sleep(60000);
}
Exception:
00:20:06,447 WARN SqlExceptionHelper:143 - SQL Error: 0, SQLState: 08S01
00:20:06,448 ERROR SqlExceptionHelper:144 - Communications link failure
The last packet successfully received from the server was 120,017 milliseconds ago. The last packet sent successfully to the server was 9 milliseconds ago.
Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Communications link failure
The last packet successfully received from the server was 120,017 milliseconds ago. The last packet sent successfully to the server was 9 milliseconds ago.
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:131)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at sun.proxy.$Proxy11.executeQuery(Unknown Source)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2031)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1832)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1811)
at org.hibernate.loader.Loader.doQuery(Loader.java:899)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:341)
at org.hibernate.loader.Loader.doList(Loader.java:2516)
at org.hibernate.loader.Loader.doList(Loader.java:2502)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2332)
at org.hibernate.loader.Loader.list(Loader.java:2327)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:124)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1621)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374)
at org.hibernate.internal.CriteriaImpl.uniqueResult(CriteriaImpl.java:396)
at com.fit.utilities.BaseDAO.getById(BaseDAO.java:35)
at com.fit.test.Testiranje.main(Testiranje.java:51)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 120,017 milliseconds ago. The last packet sent successfully to the server was 9 milliseconds ago.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1121)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3603)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3492)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4043)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2815)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2322)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
... 17 more
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:3052)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3503)
... 29 more
Here is my hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://xxxxxx:3306/xxxx</property>
<property name="connection.username">xxxx</property>
<property name="connection.password">xxxx</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">false</property>
<property name="hibernate.connection.pool_size">1</property>
<mapping class="com.xxx.model.xxxxx" />
<mapping class="com.xxx.model.xxxxx" />
<mapping class="com.xxx.model.xxxxx" />
</session-factory>
</hibernate-configuration>
UPDATE:
The problem is solved using C3P0 library.
<!-- configuration pool via c3p0-->
<property name="c3p0.acquire_increment">1</property>
<property name="c3p0.idle_test_period">100</property> <!-- seconds -->
<property name="c3p0.max_size">100</property>
<property name="c3p0.max_statements">0</property>
<property name="c3p0.min_size">10</property>
<property name="c3p0.timeout">100</property> <!-- seconds -->
The problem was happening because of the small value for time_out variable on the MySQL server.
In my situation, time_out was set to 1 minute.
Using C3PO pooling mechanism we can optimize JDBC.
Download c3p0 -> http://sourceforge.net/projects/c3p0/
I'm using hibernate 3.0.
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://databasehost:3306/databasename</property>
<property name="connection.username">user</property>
<property name="connection.password">psw</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">false</property>
<!-- Hibernate c3p0 settings-->
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.acquire_increment">3</property>
<property name="hibernate.c3p0.idle_test_period">10</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">75</property>
<property name="hibernate.c3p0.max_statements">10</property>
<property name="hibernate.c3p0.timeout">50</property>
<property name="hibernate.c3p0.preferredTestQuery">select 1</property>
<property name="hibernate.c3p0.testConnectionOnCheckout">true</property>
<!-- Mapping files -->
<mapping class="xxx.xxx.xxx.xxx" />
<mapping class="xxx.xxx.xxx.xxx" />
<mapping class="xxx.xxx.xxx.xxx" />
<mapping class="xxx.xxx.xxx.xxx" />
</session-factory>
</hibernate-configuration>
PersistenceManager.java
import java.io.PrintStream;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
public class PersistenceManager
{
private static SessionFactory sessionFactory = null;
private static PersistenceManager singleton = null;
public static PersistenceManager getInstance()
{
if (singleton == null)
{
singleton = new PersistenceManager();
}
return singleton;
}
public SessionFactory getSessionFactory()
{
if (sessionFactory == null)
createSessionFactory();
return sessionFactory;
}
protected void createSessionFactory()
{
sessionFactory = new AnnotationConfiguration().configure()
.buildSessionFactory();
}
public void destroySessionFactory()
{
if (sessionFactory != null)
{
sessionFactory.close();
sessionFactory = null;
}
}
}
Example 1:
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
public Users Login( String username, String password)
{
Session session = null;
try
{
String hql = "select u from Users u where u.username like :p1 and u.password like :p2";
session = PersistenceManager.getInstance().getSessionFactory().openSession();
Query q = session.createQuery(hql)
.setParameter("p1", username)
.setParameter("p2", password);
if (q.list().size() == 0)
{
session.close();
return new Users();
}
Users user = (Users)q.list().get(0);
session.close();
return user;
}
catch (Exception e)
{
session.close();
}
}
Example 2:
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
public String Registration(Users u) {
Session session = null;
try
{
String hql = "select u from Users u where u.username like :p1";
session = PersistenceManager.getInstance().getSessionFactory().openSession();
Query q = session.createQuery(hql).setParameter("p1", u.getUsername());
if (q.list().size() == 0)
{
session.beginTransaction();
session.persist(u);
session.getTransaction().commit();
session.close();
return new Boolean(true).toString();
}
session.close();
return new Boolean(false).toString();
}
catch (Exception e)
{
return e.toString();
}
}
I had the same issue just because I forgot to wrap my hibernate code in a transaction.
Apparently the connection to DB is not closed until you commit a transaction.
Here is a valid example:
Session session = HibernateUtils.getSession();
Transaction tx = session.beginTransaction();
Category cat = null;
try{
cat = (Category)session.get(Category.class, 1);
tx.commit();
}catch(Exception ex){
tx.rollback();
}finally{
session.close();
}
return cat;
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.
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