I have a Spring MVC project deployed on a TomCat server and I keep getting an issue with the connection to the database. After several hours, when a user tries to login they will be met with a 500 error and this message:
HTTP Status 500 - Request processing failed; nested exception is org.springframework.dao.RecoverableDataAccessException: The last packet successfully received from the server was 75,026,904 milliseconds ago. The last packet sent successfully to the server was 75,031,521 milliseconds ago. is longer than the server configured value of 'wait_timeout'.
I believe the issue is because TomCat thinks the connection to MySQL is still open, however MySQL closes the connection after 8 hours. Once you refresh the page after getting this error, everything works fine.
My question is, is there a way to have the NamedParameterJdbcTemplate, that I am using to query the database, open and close a connection each time it is used rather than maintaining one persistent connection? Or is there a better way to solve this problem?
Perhaps setting autoReconnect=true? I am trying this now, but it will take several hours before I know if it worked.
Assuming you’re using Tomcat’s connection pooling, you can set your pool to testOnBorrow=”true” and validationQuery=”SELECT 1 FROM my_test_table”. This way the connection will be checked before it’s checked out by a thread. If it’s closed, another one would be opened and given to the thread servicing your request. You can read the documentation of the options provided by Tomcat here.