Are there any settings in hibernate / spring jpa to handle connection failure and reconnecting to Hibernate and Spring JPA

I have a web application that uses Spring JPA and hibernate to connect to mysql database. If the connection to the database was to occur for any reason, I would like to catch this exception so that I can pause processing and then poll this connection forever until it returns.

Are there any settings in hibernate / spring jpa to handle this?

context.xml applications:

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName">
        <value>com.mysql.jdbc.Driver</value>
    </property>
    <property name="url">
        <value>jdbc:mysql:${db.loc}</value>
    </property>
    <property name="username">
        <value>${db.username}</value>
    </property>
    <property name="password">
        <value>${db.password}</value>
    </property>
</bean>

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
    </property>
    <property name="packagesToScan" value="com.georgelung.template" />
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.format_sql">false</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

Class TemplateRepository

@Repository
public interface TemplateRepository extends CrudRepository<TestEntity, Long> {

}
+4
source share
2 answers

, .

, .

<prop key="hibernate.connection.autoReconnect">true</prop>
<prop key="hibernate.connection.autoReconnectForPools">true</prop> 
+3

getConnection, , , , :

private Connection getConnection() {
   Connection connection = null;
   try {
       // This should return a NEW connection!
       Connection connection = dataSource.getConnection(); 
   } catch (Exception e) {
       // here you got the no connection found exception!
       System.err.println("Connection failed: " + e);
   }
   return connection;
}
+2

All Articles