Java Hibernate with SQL Server 2012 not working? - java

I have a Java Hibernate project configuration which worked with SQL Server 2008 R2, now with a new OS 8.1 (from 7) and SQL Server 2012 (express), I'm unable to connect to SQL server.
Relevant configuration which is/should be syntactically correct since it worked with 2008 R2:
datasource.properties
jdbc.driverClassName=net.sourceforge.jtds.jdbc.Driver
jdbc.url=jdbc:jtds:sqlserver://localhost:1433/dbname;instance=SQLEXPRESS
jdbc.username=auser
jdbc.password=xyz
I've tried two dialects org.hibernate.dialect.SQLServerDialect worked in 2008 R2.
hibernate.hbm2ddl.auto=create-drop
hibernate.dialect=org.hibernate.dialect.SQLServerDialect
#hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
hibernate.show_sql=true
springConfiguration.xml
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
SQL Server 2012 was installed with mixed mode authentication and SQL Server Management Studio has no problem connecting (with or without the instance name).
I've updated the SQL Server Network Configuration for SQLEXPRESS.
Protocols for SQLEXPRESS:
TCP/IP Enabled
As well as all of the TCP/IP Properties - TCP Port's to 1433.
I've tried disabling Windows Firewall just to test if it's in the way but it results in the same error.
I ended up adding Firewall rules and following some of the steps in this excellent configure SQL Express 2012 to accept remote connections article.
The error message:
Caused by: java.lang.AbstractMethodError
at net.sourceforge.jtds.jdbc.JtdsConnection.isValid(JtdsConnection.java:2833)

Your problem is jTDS does not support the way DBCP2 validates a connection by default (I'm assuming you use DBCP2 from <bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">). See the solution below.
Usually the error stacktrace is as shown:
Caused by: java.lang.AbstractMethodError
at net.sourceforge.jtds.jdbc.JtdsConnection.isValid(JtdsConnection.java:2833)
at org.apache.tomcat.dbcp.dbcp2.DelegatingConnection.isValid(DelegatingConnection.java:913)
The problem, though, is not related to the SQL Server version, but to the DBCP (Tomcat) version used (or the Tomcat server version the project is deployed to).
Once I was using jTDS 1.3.1 and the project worked fine (and connected to SQLServer 2012 as well) under Tomcat7. When I changed to Tomcat 8, that error appeared.
The reason, as hinted in jTDS forums, is:
(Tomcat7 uses DBCP 1 and Tomcat 8 uses DBCP 2)
Unlike DBCP 1.x, DBCP 2 will call java.sql.Connection.isValid(int) to validate the connection
jTDS doesn't implement .isValid(), so jTDS driver won't work with DBCP 2, unless...
...unless you set the validationQuery parameter, which will make DBCP not call .isValid() to test the validity of the connection.
Workaround
So, the workaround is to set the validationQuery parameter, which will make DBCP2 not call .isValid() to test the validity of the connection. Here's how:
On Tomcat
Add validationQuery="select 1" to your Tomcat <Resource> tag for connection pool, which is usually in META-INF/context.xml of your app or conf/server.xml:
<Resource ... validationQuery="select 1" />
On Spring
When using DBCP2 through Spring, the solution is something around:
<bean id="..." ...>
...
<property name="validationQuery" value="select 1" />
</bean>
On Simple java Code
dataSource.setValidationQuery("select 1");

It appears that jTDS has some issues with SQL Server 2012 (update 2?) or something has changed in 2012/8.1 which previously worked in 2008 R2/7.
Using nearly the same configuration as above with a couple minor changes, I downloaded and changed the datasource.properties to use Microsoft JDBC Driver 4.0 for SQL Server.
jdbc.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:sqlserver://localhost:1433;
#jdbc.url=jdbc:sqlserver://localhost\dbname:1433;
I just put the sqljdbc4.jar in tomcat\lib\ to verify that the MS JDBC driver 4.0 works with SQL Server 2012 with all updates and it works perfectly. The dialect org.hibernate.dialect.SQLServerDialect worked in 2012 too.

Related

Connect to Sql Server on liberty using mssql-jdbc

I'm trying to connect to a Sql Server database from a liberty server.
Doesn't work as I'm getting a 500 from the liberty server and the logs give me this error message: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: SQL Server did not return a response.
My xml:
<library id="sqlServerLib2" apiTypeVisibility="spec,ibm-api,api,third-party"
<fileset dir="${server.config.dir}/lib/global" includes="mssql-jdbc-6.1.0.jre8.jar"/>
</library>
<dataSource id="myDataSource" jndiName="jdbc/myDataSource">
<jdbcDriver libraryRef="sqlServerLib2"/>
<properties.microsoft.sqlserver
serverName="localhost"
portNumber="8080"
databaseName="my_db"
user="user"
password="password"/>
<connectionManager maxPoolSize="100" minPoolSize="0"/>
</dataSource>
I've looked at IBM's pages. Didn't give much help.
I've also googled the error message but people usually say that I should just update my driver to at least 4.2. I'm using 6.1, so that doesn't really apply.
What am I missing here?
Thanks.
EDIT:
I took a look at Microsoft's pages and found that i was using an incompatible jdbc-api version. I changed this from 4.0 to 4.1.
<featureManager>
<feature>jdbc-4.1</feature>
</featureManager>
I also defined the dataSource and connection pool classes in my datasource.
<jdbcDriver libraryRef="sqlserverLib2"
javax.sql.DataSource="com.microsoft.sqlserver.jdbc.SQLServerDataSource"
javax.sql.ConnectionPoolDataSource="com.microsoft.sqlserver.jdbc.SQLServerConnectionPoolDataSource"/>
Now I'm getting a java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDataSource.
I tried using the mssql-jdbc-6.1.0.jre7.jar(java 7) instead. Then all of a sudden i worked. What am I doing wrong with the jre8 version of the driver?
The main error was that I used a version of the jdbc-api that was incompatible with the mssql-jdbc-6.1.0.jre8.jar driver. Changing to version 4.1 fixed it.
The classNotFoundException was just a blunder on my part(forgot to update the pom.xml)
In your example code snippet, you have incorrect syntax for specifying the JNDI name of the data source,
<dataSource id="myDataSource" jndi="jdbc/myDataSource">
This should instead be:
<dataSource id="myDataSource" jndiName="jdbc/myDataSource">

Getting Connection timeout error when application is idle

when ever I keep my application idle for 10 or 15 hours, I will get Connection time out error. But when I frequently use my application then I couldn't able to see this error any time. Could any one please guide me whether I am making some thing wrong in the below code. This application is used by only two users and that too be not frequently.
<Context path="/****" reloadable="true">
<Resource
name="XXXX"
type="javax.sql.DataSource"
username="XXXX"
password="XXXX"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
maxIdle="4"
maxWait="30000"
initialSize="2"
url="jdbc:sqlserver://localhost;database=XXXX"
maxActive="20"/>
</Context>
Unfortunately there is not so much information given in your example. Assumed that is a small piece of a Spring (Spring Framework) context configuration, i would prefer to configure a connection pooling for the database. This pool can hold an amount of idle connections for each request an can open new ones if no connection is available in the pool for the current request. I found this piece of XML in the MySql documentation.
<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${db.driver}"/>
<property name="url" value="${db.jdbcurl}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
<property name="initialSize" value="3"/>
</bean>
Please be aware that the datasource is of type org.apache.commons.dbcp.BasicDataSource. For further information please refer to the Documentation of MySql, Spring Framework and DBCP
Based on information provided on question, i can see:
Most probably, application is not properly handling connection i.e. it is creating connection, but then somehow failed to close connection properly in application code.
As per question, if only 2 users are using this app then probably you might not able to catch connection exhausted error which usually thrown when connection pool reaches max limit.
But if you increase app users you will see your connection reached max limit very quickly.
Check number of connections that got created after application starts and observe behavior. Check if inactive connections are getting closed or not.
Also, I don't see inactive connection timeout property in configuration. Can you check if you have this property.
This is an issue with databases, it gets shutdown/locked up after a long idle period. In MySQL it is 8 hours by default. You have to use a connection pooling library like C3P0 which has configuration to talk to database and turn on the connection if it is closed.
It is possible to increase the timeout amount in databases, but not recommended. Therefor go for a system like I mentioned above which can turn on the connection for you.

Making a ms sql connection in persistence.xml in JPA

We need to make a connection to ms sql server from java persistence unit 1.0. I hace following code for oracle database.
<properties>
<property name="toplink.jdbc.url" value="jdbc:oracle:thin:#IP:PORT"/>
<property name="toplink.jdbc.user" value="####"/>
<property name="toplink.jdbc.driver" value="oracle.jdbc.driver.OracleDriver"/>
<property name="toplink.jdbc.password" value="####"/>
<property name="toplink.ddl-generation" value="create-tables"/>
<property name="toplink.jdbc.read-connections.max" value="1"/>
<property name="toplink.jdbc.read-connections.min" value="1"/>
<property name="toplink.jdbc.write-connections.max" value="1"/>
<property name="toplink.jdbc.write-connections.min" value="1"/>
<property name="toplink.logging.level" value="SEVERE" />
</properties>
I need the changes that I have to make in the previous code for making a connection to MS Sql Server.
Finally I got the solution.....
Steps to make connection to ms sql from JPA persistence.xml are:
Download the jar files from http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=21599
I chose sql server 2005 so I used sqljdbc4 jar file from the above link.
Change driver name to com.microsoft.sqlserver.jdbc.SQLServerDriver in above given xml file.
Provide necessary username and password at corresponding position in xml file.
In connection url, write jdbc:sqlserver://localhost:port;databaseName=<Database>
Microsoft SQL Server connection can be done in few ways. To use windows authentication, you need to place a dll file in your System 32 directory. After that, you can replace the
connection URL, and user credentials as required. You may need to configure your SQL server
by SQL Server Surface Configuration Manager to allow remote connections and connections through TCP IP.
After that you may try to connect through a plain java class. And after that connect using a persistence unit (in EJB?).
When you download the SQL Server - JDBC Connector ZIP file, you can find a HTML Documentation,
which you must read (it will take 20 minutes). It was a 2 day struggle for me to connect to SQL Server from JDBC.

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

I built an application and deployed locally ... and it was working perfectly. I deployed it on a remote server and started getting the exception mentioned in the subject line. It's not because of any firewall issues.
I changed my hibernate.xml to connect via my IP address rather then localhost and now I get the same timeouts on my locally deployed application. I get this error when I keep the application running for more than one day.
I am not performing any operations after committing transactions or closing sessions myself. I am using the following properties in hibernate.cfg.xml
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://myremotehost:3306/akp</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.show_sql">false</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</property>
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.Connection was implicitly closed by the driver.
Detailed:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.Connection was implicitly closed by the driver.
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 com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.Util.getInstance(Util.java:384)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1015)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:984)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:929)
at com.mysql.jdbc.ConnectionImpl.throwConnectionClosedException(ConnectionImpl.java:1193)
at com.mysql.jdbc.ConnectionImpl.checkClosed(ConnectionImpl.java:1180)
at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4137)
at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4103)
at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:505)
at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:423)
at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:139)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1547)
at org.hibernate.loader.Loader.doQuery(Loader.java:673)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
at org.hibernate.loader.Loader.doList(Loader.java:2220)
... 36 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 34,247,052 milliseconds ago. The last packet sent successfully to the server was 34,247,052 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 problem.
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 com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1118)
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3321)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1940)
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 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)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2104)
at org.hibernate.loader.Loader.list(Loader.java:2099)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:94)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1569)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:283)
at com.xyz.abc.DAO.GenericHibernateDAO.findByField(GenericHibernateDAO.java:119)
at com.xyz.abc.DAO.JobDAO.getJobsByLdap(JobDAO.java:115)
at com.xyz.abc.business.Jcr.getMyruns(Jcr.java:272)
at com.xyz.abc.business.abcService.getMyruns(abcService.java:54)
at sun.reflect.GeneratedMethodAccessor139.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.axis2.rpc.receivers.RPCUtil.invokeServiceClass(RPCUtil.java:194)
at org.apache.axis2.rpc.receivers.RPCMessageReceiver.invokeBusinessLogic(RPCMessageReceiver.java:102)
at org.apache.axis2.receivers.AbstractInOutMessageReceiver.invokeBusinessLogic(AbstractInOutMessageReceiver.java:40)
at org.apache.axis2.receivers.AbstractMessageReceiver.receive(AbstractMessageReceiver.java:114)
at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:173)
at org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:173)
at org.apache.axis2.transport.http.AxisServlet.doPost(AxisServlet.java:142)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:203)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:108)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:379)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:242)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:259)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:237)
... 4 more
Caused by: java.net.SocketException: Software caused connection abort: socket write error
Does anyone have any ideas what might cause this behavior?
EDIT:
Now am using folloing in my hibernate.cfg.xml file.Is it correct?
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/xyz</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.show_sql">false</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<!-- <property name="hibernate.c3p0.max_size">1800</property>-->
<property name="hibernate.c3p0.max_statements">50</property>
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="c3p0.max_statements">0</property>
<property name="c3p0.maxIdleTimeExcessConnections">3600</property>
<property name="c3p0.idleConnectionTestPeriod">3600</property>
<property name="c3p0.maxIdleTime">3600</property>
As #swanliu pointed out it is due to a bad connection.
However before adjusting the server timing and client timeout , I would first try and use a better connection pooling strategy.
Connection Pooling
Hibernate itself admits that its connection pooling strategy is minimal
Hibernate's own connection pooling algorithm is, however, quite
rudimentary. It is intended to help you get started and is not
intended for use in a production system, or even for performance
testing. You should use a third party pool for best performance and
stability. Just replace the hibernate.connection.pool_size property
with connection pool specific settings. This will turn off Hibernate's
internal pool. For example, you might like to use c3p0.
As stated in Reference : http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html
I personally use C3P0. however there are other alternatives available including DBCP.
Check out
http://www.mchange.com/projects/c3p0/index.html
http://commons.apache.org/dbcp/
Below is a minimal configuration of C3P0 used in my application:
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<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">1800</property> <!-- seconds -->
By default, pools will never expire Connections. If you wish
Connections to be expired over time in order to maintain "freshness",
set maxIdleTime and/or maxConnectionAge. maxIdleTime defines how many
seconds a Connection should be permitted to go unused before being
culled from the pool. maxConnectionAge forces the pool to cull any
Connections that were acquired from the database more than the set
number of seconds in the past.
As stated in Reference : http://www.mchange.com/projects/c3p0/index.html#managing_pool_size
Edit:
I updated the configuration file (Reference), as I had just copy pasted the one for my project earlier.
The timeout should ideally solve the problem, If that doesn't work for you there is an expensive solution which I think you could have a look at:
Create a file “c3p0.properties” which must be in the root of the classpath (i.e. no way to override it for particular parts of the application). (Reference)
# c3p0.properties
c3p0.testConnectionOnCheckout=true
With this configuration each connection is tested before being used. It however might affect the performance of the site.
MySQL implicitly closed the database connection because the connection has been inactive for too long (34,247,052 milliseconds ≈ 9.5 hours).
If your program then fetches a bad connection from the connection-pool that causes the MySQLNonTransientConnectionException: No operations allowed after connection closed.
MySQL suggests:
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 problem.
If you don't want use connection pool (you sure, that your app has only one connection), you can do this - if connection falls you must establish new one - call method .openSession() instead .getCurrentSession()
For example:
SessionFactory sf = null;
// get session factory
// ...
//
Session session = null;
try {
session = sessionFactory.getCurrentSession();
} catch (HibernateException ex) {
session = sessionFactory.openSession();
}
If you use Mysql, you can set autoReconnect property:
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/database?autoReconnect=true</property>
I hope this helps.
First Replace the MySQL dependency as given below
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
An error showing "Authentication plugin 'caching_sha2_password'" will appear. Run this command:
mysql -u root -p
ALTER USER 'username'#'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
Please make sure you are using latest jdbc connector as per the mysql. I was facing this problem and when I replaced my old jdbc connector with the latest one, the problem was solved.
You can download latest jdbc driver from https://dev.mysql.com/downloads/connector/j/
Select Operating System as Platform Independent. It will show you two options. One as tar and one as zip. Download the zip and extract it to get the jar file and replace it with your old connector.
This is not only for hibernate framework, it can be used with any platform which requires a jdbc connector.
This is due to using obsolete mysql-connection-java version, your MySQl is updated but not your MySQL jdbc Driver, you can update your connection jar from the official site Official MySQL Connector site.
Good Luck.

jdbc4 CommunicationsException

I have a machine running a java app talking to a mysql instance running on the same instance. the app
uses jdbc4 drivers from mysql. I keep getting com.mysql.jdbc.exceptions.jdbc4.CommunicationsException
at random times.
Here is the whole message.
Could not open JDBC Connection for transaction; nested exception is
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was25899 milliseconds ago.The last packet sent successfully to the server was 25899 milliseconds ago, which 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 problem.
For mysql, the value of global 'wait_timeout' and 'interactive_timeout' is set to 3600 seconds and 'connect_timeout' is set to 60 secs. the wait timeout value is much higher than the 26 secs(25899 msecs). mentioned in the exception trace.
I use dbcp for connection pooling and here is spring bean config for the datasource.
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource" >
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db"/>
<property name="username" value="xxx"/>
<property name="password" value="xxx" />
<property name="poolPreparedStatements" value="false" />
<property name="maxActive" value="3" />
<property name="maxIdle" value="3" />
</bean>
Any idea why this could be happening? Will using c3p0 solve the problem ?
Try setting up the Apache Commons DBCP correctly.
You need to set:
validationQuery to SELECT 1+1
testOnBorrow to true
That should fix the problem.
Can you describe how your app is handling connection pooling? I doubt that autoReconnect=true in the JDBC driver would re-pool connections from your app. The app needs to reconnect when it loses a connection.
I'd follow the advice in the exception. 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 problem. Try adding that to your connection URL (consult the docs for the exact syntax) and see if it helps.
I doubt that C3P0 will be that much better than the DBCP that you're already using. The exception is giving you some specific advice. You've tried #3. What about the other two?
I know how to ask WebLogic to check connections before using them. You should find out how to do the same with Tomcat.
I have seen before that Windows machines which have been moved on the network have had trouble with connecting to themselves.
Is there any connectivity problems outside the JVM - i.e. mysql client connecting to the server, and timing out, etc?

Categories

Resources