title: How to automatically reconnect a DataSource connection in Spring?
body: <p>Problem: when my spring application is running, and meanwhile the database server is stopped/restarted, then then db connection is lost and <em>never</em> restored.</p>
  
  <p>I tested as follows:</p>
  
  <ul>
  <li>execute query: OK</li>
  <li>service mysql stop</li>
  <li><p>execute query: exception:</p>
  
  <p>Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: </p>
  
  <p>com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.</p></li>
  <li><p>service mysql start</p></li>
  <li>execute query: still exception!</li>
  </ul>
  
  <p>Question: how can I tell spring <code>DataSource</code> to automatically reconnect after connection has been lost?</p>
  
  <p>This is my configuration:</p>
  
  <pre><code>spring.datasource.url=jdbc:mysql://localhost/tablename?useSSL=false
  spring.datasource.username=root
  spring.datasource.password=rootpw
  spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  spring.datasource.tomcat.validation-query=SELECT 1
  spring.datasource.tomcat.validation-query-timeout=5000
  spring.datasource.tomcat.test-on-borrow=true
  spring.datasource.tomcat.test-on-connect=true
  </code></pre>