Connecting Tomcat container to mysql container: JDBCConnectionException: Unable to acquire JDBC Connection - mysql

I'm trying to port my web-app created on Windows, using Hibernate, XAMPP for Apache tomcat and mysql server, to Linux, using Docker. I've deployed my war file under webapps folder on tomcat container, linked to mysql container ... the fact is that my web app is very very slow: i.e., the first feature is login/register form: on Linux, there is latency about minutes!
I've created containers with the following commands:
docker run -d --name mysql-phpmyadmin -p 127.0.0.1:8686:80 -p 127.0.0.1:3306:3306 grzesiekb/mysql-phpmyadmin
docker run -d -p 8484:8080 -p 8007:8009 --name tomcat8-linked --link mysql-phpmyadmin:mysqlphp tomcat:8.0-jre8
This is my hibernate.cfg.xml file:
<!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>
<!-- queste configurazioni sono per il testing in locale -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://mysqlphp:3306/at_db</property>
<property name="hibernate.connection.username">root</property>
<property name="connection.password">mysql_pass</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>
<property name="show_sql">false</property>
<!--<property name="hibernate.hbm2ddl.auto">create-drop</property> se al posto di update metto create, mi cancella il db e lo rifa -->
<property name="hbm2ddl.auto">update</property>
<!-- Entity -->
<mapping class="com.ATBoscoCastellano.Entity.ClientUser" />
<mapping class="com.ATBoscoCastellano.Entity.GenericUser" />
<mapping class="com.ATBoscoCastellano.SessionManagement.SessionToken" />
<mapping class="com.ATBoscoCastellano.Entity.Post" />
<!-- <mapping class="it.boscus.StarFoods.entity.ExampleEmbeddableIDClass2" /> -->
</session-factory>
</hibernate-configuration>
And this is what I see from tomcat logs:
20-Feb-2017 07:48:15.869 SEVERE [http-apr-8080-exec-3] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [com.ATBoscoCastellano.servlets.UserSessionServlet] in context with path [/AtApplicazione1] threw exception
org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:115)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
....
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 232,149,705 milliseconds ago. The last packet sent successfully to the server was 232,149,705 milliseconds ago. is longer than the server configured
value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this probl
em.
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:404)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:983)
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3644)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2452)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2617)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2546)
at com.mysql.jdbc.ConnectionImpl.setAutoCommit(ConnectionImpl.java:4873)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.poll(PooledConnections.java:76)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:187)
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:386)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:84)
... 34 more
Caused by: java.net.SocketException: Broken pipe (Write failed)
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:111)
at java.net.SocketOutputStream.write(SocketOutputStream.java:155)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
I've tried adding autoReconnect=true on Url in hibernate, but still doesn't work. In my mysql my.cnf there is no wait_timeout line.
I have to tell that web-app works, but i attend a lot of time (tens of minutes) after my servlet (that interacts via hibernate with mysql container) works. This servlet, that manages login/register form, checks from the db the eventual presence of the inserted credentials.
I have tomcat container based on tomcat8.0-jre8 official docker image;
From mysql -V I have
root#1c53f40b63d3:/var/log/mysql# mysql -V
mysql Ver 14.14 Distrib 5.5.42, for debian-linux-gnu (x86_64) using readline 6.3
I really don't know why on Windows it works perfectly, but here not. My servlet remain in "pending" state ... i really want to know why there is so spending in time and how to solve it.

Related

Unable to connect with MySql Database hosted on Amazon Web Server

Error Type
Type Exception Report
Message Request processing failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
I have created a simple Spring Mvc application that connects with the database, everything works well locally, ie localhost:8080
But when i hosted that in aws,i am not able to connect my application with the database.i created data bases and tables in mysql of aws.
<!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>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://34.201.126.236:3306/dbName?useSSL=false</property>
<property name="connection.username">root</property>
<property name="connection.password">secretPassword</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">10</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
What is the Problem?

Connect a web-app on tomcat container to mysql container via hibernate

i'm trying to port my web-app from windows (using xampp for apache+mysql) to ubuntu (using docker container, so i have two containers: one with tomcat and another one with mysql.. they're linked).
Related to this question, i can't reach my sql container. It's creted from this image.
Tomcat container is created from official tomcat:8.0 image.
The two container are linked via a bridge docker network created.
It's a web-app that provides login+register service with checking user's presence in db.
I have to tell that on windows all works well.
This is my hibernate.cfg file:
<!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>
<!-- queste configurazioni sono per il testing in locale -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:49162/AT_DB</property>
<property name="hibernate.connection.username">root</property>
<property name="connection.password">lxit</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>
<property name="show_sql">false</property>
<!--<property name="hibernate.hbm2ddl.auto">create-drop</property> se al posto di update metto create, mi cancella il db e lo rifa -->
<property name="hbm2ddl.auto">update</property>
<!-- Entity -->
<mapping class="com.ATBoscoCastellano.Entity.ClientUser" />
<mapping class="com.ATBoscoCastellano.Entity.GenericUser" />
<mapping class="com.ATBoscoCastellano.SessionManagement.SessionToken" />
<mapping class="com.ATBoscoCastellano.Entity.Post" />
<!-- <mapping class="it.boscus.StarFoods.entity.ExampleEmbeddableIDClass2" /> -->
</session-factory>
</hibernate-configuration>
After i insert my credential, i click on "login"; then there is a servlet named "UserSessionServlet" that checks if in the db is present an user with that credential; the error appairs when i click login, because UserSessionServlet return http 500 error.
[Edit] On tomcat container, i saw that logs tell me:
16-Feb-2017 09:43:41.498 SEVERE [http-nio-8080-exec-19] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [com.ATBoscoCastellano.servlets.UserSessionServlet] in context with path [/AtApplicazione1] threw exception [Servlet execution threw an
exception] with root cause
java.lang.NoClassDefFoundError: Could not initialize class com.ATBoscoCastellano.Util.HibernateUtil.HibernateUtil
at com.ATBoscoCastellano.Entity.GenericUser.checkIfUserExistsByEmail(GenericUser.java:198)
at com.ATBoscoCastellano.Entity.ClientUser.validateCredentials(ClientUser.java:259)
at com.ATBoscoCastellano.servlets.UserSessionServlet.doPost(UserSessionServlet.java:78)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:509)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1104)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
But all these classes exist, under opt/tomcat/webapps/AtApplicazione1/WEB-INF/classes/com/AtBoscoCastellano/some/paths.
I have to tell that i've not modified my tomcat container from official image (tomcat:8.0), so i can't know if it's configured for hibernate or not.
My war is structured as follows: three folders (META-INF, WEB-INF, template) and a file (.DS_Store). Because of my exception is :java.lang.NoClassDefFoundError: Could not initialize class com.ATBoscoCastellano.Util.HibernateUtil.HibernateUtil , in the war, this class is under WEB-INF/classes/com/ATBoscoCastellano/Util/HibernateUtil/ ... in which there is HibernateUtil .class and .java.
When i cmd java/javac -version on my tomcat container, its output is:
root#a26ff8018f3f:/opt/tomcat# java -version
java version "1.8.0_111"
Java(TM) SE Runtime Environment (build 1.8.0_111-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.111-b14, mixed mode)
root#a26ff8018f3f:/opt/tomcat# javac -version
javac "1.8.0_111"
[re-edit]: in my first requests, catalina logs says java.net.ConnectException: Connection refused; then, from the second request, it says to me always the same error.
[EDIT] now i'm using a new mysql container, named mysql-phpmyadmin from this image. I've linked tomcat container to this (new) container,; if i point, in the hibernate.cfg.xml, to localhost:PORT_MYSQL/AT_DB --> connection refused in tomcat log. If i point to mysql-phpmyadmin:PORT/AT_DB, tomcat logs says:
17-Feb-2017 08:31:25.649 SEVERE [http-apr-8080-exec-2] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [com.ATBoscoCastellano.servlets.UserSessionServlet] in context with path [/AtApplicazione1] threw exception [Servlet execution threw an e
xception] with root cause
java.sql.SQLException: null, message from server: "Host '172.17.0.9' is not allowed to connect to this MySQL server"
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:959)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1038)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2254)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2285)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2084)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:795)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44)
I have to tell that, in config file within mysql container, there is bind_address 0.0.0.0
I think I have an idea why you are getting this exception. You are running 2 containers,
mysql container for data base
Tomcat container
Surely, your exception is due to static variable initialization exception,
public static final SessionFactory sessionFactory = buildSessionFactory();
Also, your property file has few problems,
connection.url should be hibernate.connection.url
You have mentioned your mysql hostname as localhost but it is running in another container. You should change it to "mysql" if you have named your mysql container as "mysql"
java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:214)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:298)
Clearly shows that your either
Mysql is not runnning. Check by making a connection from sql client like squirrel.
Tomcat container can't connect to mysql container. Check a quick ping by doing
docker exec tomcat ping mysql
Took me a while to deploy this application. I have solved the problem you have asked in this question. The primary problem was that mysql was not reachable from tomcat container. Also, the port specified was also not correct. Following is hibernate.cfg.xml,
<!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>
<!-- queste configurazioni sono per il testing in locale -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://mysql:3306/AT_DB</property>
<property name="hibernate.connection.username">root</property>
<property name="connection.password">lxit</property>
....rest of configuration....
</session-factory>
</hibernate-configuration>
There are few problems like following,
17-Feb-2017 16:07:53.156 INFO [http-nio-8080-exec-1] org.hibernate.dialect.Dialect.<init> HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
17-Feb-2017 16:07:53.776 INFO [http-nio-8080-exec-1] org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.processGetTableResults HHH000262: Table not found: ClientUser
17-Feb-2017 16:07:53.777 INFO [http-nio-8080-exec-1] org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.processGetTableResults HHH000262: Table not found: ClientUser
17-Feb-2017 16:07:53.818 INFO [http-nio-8080-exec-1] org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.processGetTableResults HHH000262: Table not found: Post
17-Feb-2017 16:07:53.819 INFO [http-nio-8080-exec-1] org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.processGetTableResults HHH000262: Table not found: Post
17-Feb-2017 16:07:53.828 INFO [http-nio-8080-exec-1] org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.processGetTableResults HHH000262: Table not found: SessionToken
17-Feb-2017 16:07:53.828 INFO [http-nio-8080-exec-1] org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.processGetTableResults HHH000262: Table not found: SessionToken
17-Feb-2017 16:07:53.830 WARN [http-nio-8080-exec-1] org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl.handleException GenerationTarget encountered exception accepting command : Unable to execut
But these are due to case sensitivity of unix which was probably not there in case of Windows. Rest of the exception are trivial to solve. I ran following docker commands,
sudo docker run -ti --rm -p 8888:8080 -p 8009:8009 -v $(pwd):/usr/local/tomcat/webapps/ --name tomcat tomcat:9-jre8 bash
sudo docker run -d --name mysql -p 49162:3306 -p 49161:80 -p 49160:22 lxitgto/mysql-phpmyadmin:v1
and rest of the network command.

Mysql connection URL openshift

How do I see MySql connection URL from openshift? I need it to use it in hibernate.cfg.xml
When I log onto my account online I only see the username and password.
On open shift the database is already available in JNDI. It's name is jdbc/MySQLDS.
To use this 'datasource' in hibernate, your hibernate.cfg.xml should look something like this:
<!-- Database connection settings -->
<property name="hibernate.connection.datasource">java:comp/env/jdbc/MySQLDB</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Mapped annotated entity-->
<mapping class="org.hibernate.tutorial.domain.Event"/>
</session-factory>
To help you even mote please tell us if you are using JbossEWS 1.0, 2.0, JBoss AS6, JBoss EAP. Is your app scale, etcetera.

Hibernate, c3p0, and Mysql, spring

Many related issues are there at stack overflow but still i am putting this because still i haven't clear solution and exact reason for my problem.
I hope here i get complete solution of my problem and help full for All
I am using c3p0, MySQL, hibernate(J PA) and spring in my application.
Listing of main jar files i am using in my application is:
c3p0-0.9.2.jar
mchange-commons-java-0.2.3.3.jar
hibernate-commons-annotations-3.0.0.ga.jar
hibernate-entity manager.jar
hibernate-tools.jar
hibernate-validator-4.0.2.GA.jar
hibernate3.jar
mysql-connector-java-5.1.13-bin.jar
c3p0 settings in my persistent.XML is like this:
<property name="hibernate.c3p0.timeout" value="300"/>
<property name="hibernate.c3p0.max_statements" value="50"/>
<property name="hibernate.c3p0.idle_test_period" value="300"/>
Here that somewhere i read that hibernate.c3p0.idle_test_period must
not be higher of the hibernate.c3p0.timeout. In my case both are equal.
Is i need to change anything ?
how can i solve this problem ?
Server works fine for some hours(may be till 8 hours not exactly) and gives following error. error log is:
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failure
The last packet successfully received from the server was 35,019,246 milliseconds
ago. The last packet sent successfully to the server was 0 milliseconds ago.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1118)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3055)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2941)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3489)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2113)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2275)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery
(NewProxyPreparedStatement.java:116)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:186)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1787)
at org.hibernate.loader.Loader.doQuery(Loader.java:674)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
at org.hibernate.loader.Loader.doList(Loader.java:2220)
... 39 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:2502)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2952)
... 52 more
... 39 more
Caused by: java.net.SocketException: Broken pipe
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3302)
... 50 more
Here I am showing the snapshot of my persistent.xml:-
<properties>
<property name="hibernate.connection.username" value="****"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.password" value="***************"/>
<property name="hibernate.connection.url" value="jdbc:mysql://xxx.xxx.x.xx:3306/projectname?autoReconnect=true"/>
<!--Connection Pooling c3p0 configuration-->
<!--Minimum number of JDBC connections in the pool. Hibernate default: 1-->
<property name="hibernate.c3p0.min_size" value="5"/>
<!--Maximum number of JDBC connections in the pool. Hibernate default: 100-->
<property name="hibernate.c3p0.max_size" value="20"/>
<!--When an idle connection is removed from the pool (in second). Hibernate default: 0, never expire.-->
<property name="hibernate.c3p0.timeout" value="300"/>
<!--Number of prepared statements will be cached. Increase performance. Hibernate default: 0 , caching is disable.-->
<property name="hibernate.c3p0.max_statements" value="50"/>
<!--idle time in seconds before a connection is automatically validated. Hibernate default: 0-->
<property name="hibernate.c3p0.idle_test_period" value="300"/>
</properties>
I use singleton object of connection class in my application.
public static void createConnection()
{
if (em != null)
{
Connection.em.clear();
}
if (em == null) {
new Connection();
}
Thanks in advance. Hope i will get my solution.
--Om--
A singleton Connection object is a bad idea (at least it is in any concurrent, multi-client application). It is certainly inconsistent with a Connection pool, the philosophy of which is that Connections should be acquired from the pool when they are needed and returned to the pool [by calling close()] as soon as a unit of work is done.
Right now, your singleton Connection will timeout, and there is nothing c3p0 can do about it. Connection pools manage and test Connections when they are checked into the pool. When they are checked out, the pool tries to stay out of the way and not interfere with the client.
==> All of that said, it's unclear what your "Connection" class is here. It looks like it is not a java.sql.Connection after all, because you have a static field called "em" in Connection. So it is hard to interpret what's going on.
Broadly, you want a single c3p0 DataSource, and to acquire Connections as-needed and to close() them as promptly as possible.
To prevent Connection timeouts like you are seeing, the best approach a Connection testing regime. The easiest approach would be to set...
hibernate.c3p0.validate=true
hibernate.c3p0.preferredTestQuery=SELECT 1
Once you have that working, you can enhance the performance a bit by using testConnectionOnCheckin and idleConnectionTestPeriod (or hibernate.c3p0.idle_test_period). See http://www.mchange.com/projects/c3p0/#configuring_connection_testing
It makes no sense to have your idleConnectionTestPeriod (hibernate.c3p0.idle_test_period) and maxIdleTime (hibernate.c3p0.timeout) be the same. Idle connections will never be tested; they'll expire before they get the chance. idleConnectionTestPeriod (hibernate.c3p0.idle_test_period), if you set it at all, should be much shorter than maxIdleTime (hibernate.c3p0.timeout).
Good luck!
As this is the first hit in Google I'll share what brought me the solution to this problem showing up on our production servers: http://drglennn.blogspot.nl/2009/05/javasqlsqlexception-communication-link.html
What made this a nasty bug is that the application will work by ommitting:
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
in your persistence-unit config but it will not use the C3P0 Connection Pool and will therefore generate connection failures.
Caused by: CommunicationsException: Communications link failure
That exception means Database isn't reachable.
Since you are able to connect to Database I guess issue might be
1) DB server is down at that time
2) DB server has run out of connections.
Try connecting to Database using some other tool, MySQL Workbench or from console, at the time you get this exception
You should rater configure you a datasource. Otherwise there is much trouble with the interaction of spring an c3o0.
<bean id="dataSource_core" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${hibernate.connection.driver_class}" />
<property name="jdbcUrl" value="${hibernate.connection.url}" />
<property name="user" value="${hibernate.connection.username}" />
<property name="password" value="${hibernate.connection.password}" />
<property name="minPoolSize" value="${hibernate.connection.minPoolSize}" />
<property name="maxPoolSize" value="${hibernate.connection.maxPoolSize}" />
<property name="maxIdleTime" value="${hibernate.connection.maxIdleTime}" />
<property name="maxStatements" value="${hibernate.connection.maxStmts}" />
<property name="testConnectionOnCheckout" value="${hibernate.connection.testCo}" />
<property name="testConnectionOnCheckin" value="${hibernate.connection.testCo}" />
<property name="preferredTestQuery" value="${hibernate.connection.testSQL}" />
<property name="idleConnectionTestPeriod" value="${hibernate.connection.testPeriod}" />
</bean>

Can't find mysql.jdbc.Driver - MySQL, JBoss

I'm unable to deploy my web app with MySQL 5.5.11 backend to JBoss 5. I get this error:
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver from BaseClassLoader#262b2310
I pasted my stack trace below.
Here's what I've done...
I added mysql-connector-java-5.1.14-bin.jar to {JBOSS_HOME}/lib (that connector should work with MySQL 5.5.11 right?). I also added mysql-ds.xml to {JBOSS_HOME}/server/default/deploy.
<datasources>
<local-tx-datasource>
<jndi-name>MySqlDS</jndi-name>
<connection-url>jdbc:mysql://localhost:3306/my_libl_db</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<user-name>root</user-name>
<password>test</password>
<exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
</local-tx-datasource>
</datasources>
Also, I made sure the mysql-connector-java-5.1.14-bin.jar in my lib folder is in my web apps classpath. In the JBoss Admin Console, under Resources/Datasources, I do see MySqlDS with a status of up.
My project (in Eclipse Indego Release) is an Enterprise Application Project with 1 Dynamic Web Project. The web app has has an #Entity bean and a #Stateless bean. The #Stateless is being injected to a servlet (using #EJB). Here's 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="ContactBookPersistUnit" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/MySqlDS</jta-data-source>
<class>com.contact.model.Contact</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
</persistence>
What could I be doing wrong?
Caused by: javax.resource.ResourceException: Unable to get managed connection for MySqlDS
at org.jboss.resource.connectionmanager.BaseConnectionManager2.getManagedConnection(BaseConnectionManager2.java:441)
at org.jboss.resource.connectionmanager.TxConnectionManager.getManagedConnection(TxConnectionManager.java:381)
at org.jboss.resource.connectionmanager.BaseConnectionManager2.allocateConnection(BaseConnectionManager2.java:496)
at org.jboss.resource.connectionmanager.BaseConnectionManager2$ConnectionManagerProxy.allocateConnection(BaseConnectionManager2.java:941)
at org.jboss.resource.adapter.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:89)
... 65 more
Caused by: org.jboss.resource.JBossResourceException: Could not create connection; - nested throwable: (org.jboss.resource.JBossResourceException: Failed to register driver for: com.mysql.jdbc.Driver; - nested throwable: (java.lang.ClassNotFoundException: com.mysql.jdbc.Driver from BaseClassLoader#262b2310{VFSClassLoaderPolicy#5a0b0303{name=vfszip:/Users/Albert/DEV/Servers/JBoss5/server/default/deploy/ContactBook.ear/ContactBookWeb.war/ domain=ClassLoaderDomain#5e33f929{name=vfszip:/Users/Albert/DEV/Servers/JBoss5/server/default/deploy/ContactBook.ear/ContactBookWeb.war/ parentPolicy=AFTER_BUT_JAVA_BEFORE parent=BaseClassLoader#7cdd93a5{vfszip:/Users/Albert/DEV/Servers/JBoss5/server/default/deploy/ContactBook.ear/}} roots=[ZipEntryHandler#150136868[path=ContactBook.ear/ContactBookWeb.war/WEB-INF/classes context=file:/Users/Albert/DEV/Servers/JBoss5/server/default/deploy/ real=file:/Users/Albert/DEV/Servers/JBoss5/server/default/deploy/ContactBook.ear/ContactBookWeb.war/WEB-INF/classes]] delegates=null exported=[, com.contact.servlet, com.contact.service, com.contact.model, com.contact.control, META-INF] <IMPORT-ALL>NON_EMPTY}}))
at org.jboss.resource.adapter.jdbc.local.LocalManagedConnectionFactory.getLocalManagedConnection(LocalManagedConnectionFactory.java:225)
at org.jboss.resource.adapter.jdbc.local.LocalManagedConnectionFactory.createManagedConnection(LocalManagedConnectionFactory.java:195)
at org.jboss.resource.connectionmanager.InternalManagedConnectionPool.createConnectionEventListener(InternalManagedConnectionPool.java:633)
at org.jboss.resource.connectionmanager.InternalManagedConnectionPool.getConnection(InternalManagedConnectionPool.java:267)
at org.jboss.resource.connectionmanager.JBossManagedConnectionPool$BasePool.getConnection(JBossManagedConnectionPool.java:622)
at org.jboss.resource.connectionmanager.BaseConnectionManager2.getManagedConnection(BaseConnectionManager2.java:404)
... 69 more
Caused by: org.jboss.resource.JBossResourceException: Failed to register driver for: com.mysql.jdbc.Driver; - nested throwable: (java.lang.ClassNotFoundException: com.mysql.jdbc.Driver from BaseClassLoader#262b2310{VFSClassLoaderPolicy#5a0b0303{name=vfszip:/Users/Albert/DEV/Servers/JBoss5/server/default/deploy/ContactBook.ear/ContactBookWeb.war/ domain=ClassLoaderDomain#5e33f929{name=vfszip:/Users/Albert/DEV/Servers/JBoss5/server/default/deploy/ContactBook.ear/ContactBookWeb.war/ parentPolicy=AFTER_BUT_JAVA_BEFORE parent=BaseClassLoader#7cdd93a5{vfszip:/Users/Albert/DEV/Servers/JBoss5/server/default/deploy/ContactBook.ear/}} roots=[ZipEntryHandler#150136868[path=ContactBook.ear/ContactBookWeb.war/WEB-INF/classes context=file:/Users/Albert/DEV/Servers/JBoss5/server/default/deploy/ real=file:/Users/Albert/DEV/Servers/JBoss5/server/default/deploy/ContactBook.ear/ContactBookWeb.war/WEB-INF/classes]] delegates=null exported=[, com.contact.servlet, com.contact.service, com.contact.model, com.contact.control, META-INF] <IMPORT-ALL>NON_EMPTY}})
at org.jboss.resource.adapter.jdbc.local.LocalManagedConnectionFactory.getDriver(LocalManagedConnectionFactory.java:489)
at org.jboss.resource.adapter.jdbc.local.LocalManagedConnectionFactory.getLocalManagedConnection(LocalManagedConnectionFactory.java:206)
... 74 more
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver from BaseClassLoader#262b2310{VFSClassLoaderPolicy#5a0b0303{name=vfszip:/Users/Albert/DEV/Servers/JBoss5/server/default/deploy/ContactBook.ear/ContactBookWeb.war/ domain=ClassLoaderDomain#5e33f929{name=vfszip:/Users/Albert/DEV/Servers/JBoss5/server/default/deploy/ContactBook.ear/ContactBookWeb.war/ parentPolicy=AFTER_BUT_JAVA_BEFORE parent=BaseClassLoader#7cdd93a5{vfszip:/Users/Albert/DEV/Servers/JBoss5/server/default/deploy/ContactBook.ear/}} roots=[ZipEntryHandler#150136868[path=ContactBook.ear/ContactBookWeb.war/WEB-INF/classes context=file:/Users/Albert/DEV/Servers/JBoss5/server/default/deploy/ real=file:/Users/Albert/DEV/Servers/JBoss5/server/default/deploy/ContactBook.ear/ContactBookWeb.war/WEB-INF/classes]] delegates=null exported=[, com.contact.servlet, com.contact.service, com.contact.model, com.contact.control, META-INF] <IMPORT-ALL>NON_EMPTY}}
at org.jboss.classloader.spi.base.BaseClassLoader.loadClass(BaseClassLoader.java:448)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at org.jboss.resource.adapter.jdbc.local.LocalManagedConnectionFactory.getDriver(LocalManagedConnectionFactory.java:474)
This bit of documentation says you need to add the JAR to the /lib file in your default server configuration:
http://docs.jboss.org/jbossas/getting_started/v4/html/db.html
UPDATE: JBOSS 6 and newer has been rewritten to be more modular. You have to add JBDC drivers to your /module directory.