We faced similar problem in our project, and added the following in our DataSource beans for every database we were using.
Code:
<bean id="newDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<!-- userid, password etc. other properties -->
<property name="validationQuery">
<value>select 1</value>
</property>
<property name="maxIdle">
<value>5</value>
</property>
<property name="maxActive">
<value>20</value>
</property>
<property name="initialSize">
<value>5</value>
</property>
<property name="timeBetweenEvictionRunsMillis">
<value>1800000</value>
</property>
<property name="testWhileIdle">
<value>true</value>
</property>
<property name="testOnBorrow">
<value>false</value>
</property>
</bean>
Here the validationQuery property makes query "select 1" (as specified) before every database operation. And it allows the actual database operation (that you intended) to be performed only when the above query is successfully executed. So it keeps firing the above query continuously until it is executed successfully. Also, the first request after the idle period may take slightly longer to execute for the same reason.
Please note that this solution is kind of expensive and you may have to look for alternatives again. We have not put this on production yet, but on QA it works fine.
Also,
this link may prove helpful