Java Hibernate 与数据库的连接在几分钟后超时

Java Hibernate connection to database timed out after few minutes

Hibernate 在几分钟后失去与数据库的连接并发送这样的错误:

org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions WARN:

SQL Error: 0, SQLState: 08S01 paź 18, 2018 11:17:40 PM

org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions ERROR:

The last packet successfully received from the server was 363 452 milliseconds ago. The last packet sent successfully to the server was 363 493 milliseconds ago. is longer than the server configured value of 'interactive_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.

我添加了 autoreconnect=true 但它没有用,错误仍然出现。

然后我创建了具有以下功能的 DatabaseConnectionController:

public static EntityManagerFactory getEntityManagerFactory() {

    if (entityManagerFactory != null && entityManagerFactory.isOpen()) {
        return entityManagerFactory;
    } else {
        return requestNewConnection();
    }
}

问题依旧,我开始在google中寻找答案,我在persistance.xml中添加了几行:

<property name="hibernate.dbcp.validationQuery" value="SELECT 1" />
<property name="hibernate.dbcp.testOnBorrow" value="true" />
<property name="hibernate.dbcp.validationInterval" value="60000" />
<property name="hibernate.dbcp.testOnReturn" value="true" />

同样没有解决我的问题

Hibernate 第一次发送错误消息时不会自动重新连接到数据库,但是在发送第二次查询时会自动重新连接到数据库。

如何设置它在断开连接后自动重新连接,或者如何捕获此错误并在代码中重复查询?

问题是数据库会丢弃空闲连接。连接可以空闲多长时间取决于您的数据库配置。为了解决这个问题,你需要使用一个连接池,比如 c3p0。要使用它,您需要在 Maven 中添加以下依赖项。

<!-- c3p0 -->
<!-- Session manager -->
<!-- Check that the version works for you -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-c3p0</artifactId>
    <version>5.2.12.Final</version>
</dependency>

然后你需要在你的hibernate.cfg.xml.

中添加以下配置
<!-- c3p0 -->
<property name="hibernate.c3p0.acquire_increment">1</property>
<property name="hibernate.c3p0.idle_test_period">300</property>
<property name="hibernate.c3p0.timeout">600</property>
<property name="hibernate.c3p0.max_size">25</property>
<property name="hibernate.c3p0.min_size">1</property>
<property name="hibernate.c3p0.max_statement">0</property>
<property name="hibernate.c3p0.acquireRetryAttempts">1</property>
<property name="hibernate.c3p0.acquireRetryDelay">250</property>

这应该足以继续创建新连接并解决您的连接问题。