title: Spring Data JPA with ssh tunnel to a remote MySQL server
body: <p>I'm using Spring Data JPA  with Hibernate as persistence provider in conjunction with a remote MySQL5 Server for a job that periodically replicates a subset of internal data. The job (i.e. a quartz-scheduled java application) runs once per dai and needs approx. 30seconds to complete the synchronization). For safety reasons we don't want to open the remote server for direct connections from outside (i.e. other than localhost).</p>
  
  <p>I've seen examples with Jsch to programmatically  set up an ssh tunnel, but could not finde any resources on how to integrate Jsch with spring data. One problem I'm seeing is that certain of my spring beans (i.e. org.apache.commons.configuration.DatabaseConfiguration) are created at application startup and already needs access to the datasource. </p>
  
  <p>I could open the ssh tunnel outside of the application, but then it would be opened all the time, but I wanted to avoid that as I only need it opened 30seconds per day.</p>
  
  <p>EDIT:</p>
  
  <p>After some research I found several ways to get a ssh tunnel</p>
  
  <p>A) Implementing my own DataSource (I extended org.springframework.jdbc.datasource.DriverManagerDataSource) and then used PostContruct and Predestroy to setup / close the ssh tunnel with Jsch</p>
  
  <p>--> Problem: The ssh tunnel remains open for the lifetime of the application, what is not what I want</p>
  
  <p>B) Implementing my own Driver (I extended com.mysql.jdbc.Driver) and overwrite "connect" to create the ssh tunnel before the connection</p>
  
  <p>--> Problem: I'm not able to close the ssh tunnel connection </p>
  
  <p>Any more suggestions are welcome</p>