Reputation: 915
I have a web app which uses Spring JPA and hibernate to connect to a mysql database. If the connection to the database were to drop for whatever reason I would like to catch that exception, so that I can pause processing, and then poll that connection forever until it comes back up.
Are there any settings within hibernate/spring jpa to cope with this?
application-context.xml:
<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>
TemplateRepository class
@Repository
public interface TemplateRepository extends CrudRepository<TestEntity, Long> {
}
Upvotes: 4
Views: 1001
Reputation: 27003
You need to create a getConnection
method like this to ensure you have a valid connection before trying to connect to the DB:
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;
}
Upvotes: 2
Reputation: 2325
Why to capture connection loss with database and try to reconnect manually when hibernate provide this solution out of box
Add below code in your hibernate configuration should resolve your issue
<prop key="hibernate.connection.autoReconnect">true</prop>
<prop key="hibernate.connection.autoReconnectForPools">true</prop>
Upvotes: 3