休眠/弹簧 jpa 中是否有任何设置来应对连接失败以及与休眠和弹簧 JPA 的重新连接



我有一个使用Spring JPA和休眠连接到mysql数据库的Web应用程序。如果与数据库的连接由于任何原因而断开,我想捕获该异常,以便我可以暂停处理,然后永久轮询该连接,直到它恢复。

休眠/春季 jpa 中是否有任何设置来应对此问题?

应用程序上下文.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>

模板存储库类

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

为什么要捕获数据库的连接丢失并尝试在休眠时手动重新连接 提供开箱即用的解决方案

在休眠配置中添加以下代码应该可以解决您的问题

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

您需要创建一个这样的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;
}

最新更新