Java – DBCP and Hibernate do not reopen the dead connection on spring. Why?
I am using hibernate and DBCP to manage MySQL connections, both in the spring project
Everything is normal The only problem is that if the application stays for a long time, it will throw an exception because the connection is dead (the same thing, if I restart mysqld, when the application starts) This is not a big deal because the user will get the exception page (or custom), and reloading will solve the problem But I want to solve it This is part of the exception:
com.MysqL.jdbc.CommunicationsException: Communications link failure due to underlying exception:
**Start deduction**
java. io. Message of eofexception: unable to read response from server Expected to read 4 bytes, read 0 bytes, connection lost unexpectedly
Stack trace:
java. io. Eofexception: unable to read response from server Expected to read 4 bytes, connection lost unexpectedly
I googled. I found that with MySQL, I should put DBCP The basicdatasource property testonmirror is set to true, which is what I found in servlet context Completed in XML:
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.MysqL.jdbc.Driver" /> <property name="url" value="jdbc:MysqL://${MysqL.host}/${MysqL.db}" /> <property name="username" value="${MysqL.user}" /> <property name="password" value="${MysqL.pass}" /> <property name="testOnBorrow" value="true"></property> </bean>
But the problem remains Any clues?
Solution! I used:
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.MysqL.jdbc.Driver" /> <property name="url" value="jdbc:MysqL://${MysqL.host}/${MysqL.db}" /> <property name="username" value="${MysqL.user}" /> <property name="password" value="${MysqL.pass}" /> <property name="testOnBorrow" value="true"></property> <property name="validationQuery" value="SELECT 1"></property> </bean>
Solution
If you set testonmirror, you must also set validationquery –
I also set timebetween evictionrunsmillis, so dead connections will be evicted from the pool