Last week after releasing first version of Wicket, Spring and JDBC based application into production I noticed strange behavior. Everyday first attempt to enter the service caused unexpected exception. Quick glance at Tomcat logs showed code presented below:

It looks that after few hours at night when no-one used the application, MySQl server closed connection and first database query caused exception. I double checked my connection url and settings in context.xml file to found nothing obviously wrong:

I had used the same settings in pure JDBC projects few times before and never encoutered similar exception so now I wanted to ask uncle Google for some answers 🙂 At the beginning I dove into the MySQL manual to check why autoReconnect isn’t enough in my application but found nothing relevant to my problem. After some thinking I got the idea that maybe some settings in Commons-DBCP are missing so I read dbcp configuration to find that connection could be validated before real usage by specifing two parameters: testOnBorrow=“true” validationQuery=“select 1” . As written in docs:

testOnBorrow – The indication of whether objects will be validated before being borrowed from the pool. If the object fails to validate, it will be dropped from the pool, and we will attempt to borrow another. NOTE – for a true value to have any effect, the validationQuery parameter must be set to a non-null string.
validationQuery – The SQL query that will be used to validate connections from this pool before returning them to the caller. If specified, this query MUST be an SQL SELECT statement that returns at least one row.

After adding these two parameters to context.xml my problems disappeared.