Hibernate连接数据库超时设置

本文介绍了当使用MySQL数据库时遇到连接超时的情况及其解决方案。包括调整MySQL配置、使用c3p0连接池以及在Hibernate配置中加入特定属性等方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

com.MySQL.jdbc.CommunicationsException: The last packet successfully received from the server was58129 seconds ago.The last packet sent successfully to the server was 58129 seconds ago, which is longer than the server configured value of 'wait_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.
解决办法:
如果连接闲置8小时 (8小时内没有进行数据库操作), mysql就会自动断开连接, 要重启tomcat. 
不用hibernate的话, connection url加参数: autoReconnect=true 
用hibernate的话, 加如下属性:

<property name="connection.autoReconnect">true</property> 
<property name="connection.autoReconnectForPools">true</property> 
<property name="connection.is-connection-validation-required">true</property>

要是还用c3p0连接池: 
<property name="hibernate.c3p0.acquire_increment">1</property> 
<property name="hibernate.c3p0.idle_test_period">0</property> 
<property name="hibernate.c3p0.timeout">0</property> 
<property name="hibernate.c3p0.validate">true</property>

或者最王道的解决办法,那就是直接修改mysql的配置文件my.ini 在配置文件的最后增加wait_timeout=343232后面的数字是以秒计算。改个10年100年多方便的。

另外的解决办法:

解决hibernate+mysql出现的隔天连接超时问题

出现错误:SQL Error: 0, SQLState: 08S01
Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
Java.NET.SocketException
MESSAGE: Software caused connection abort: socket write error
STACKTRACE:
java.Net.SocketException: Software caused connection abort: socket write error
** END NESTED EXCEPTION **
Last packet sent to the server was 0 ms ago

问题出现原因
mysql默认为8小时后自动消除空闲连接,而hibernate默认空连接超时时间大于这个数。

解决方法
1.找到mysql5.0目录下的my.ini文件,在最底处(或任意位置)添加wait_timeout =60(60为自定义值)
2.用c3p0代替hibernate的连接池。c3p0.9.1.jar可从hibernate开源项目的lib下面找到,将其拷贝到web-inf/lib下面。在hibernate.cfg.xml配置文件中添加以下信息:
<property name="hibernate.c3p0.min_size">2</property>
<property name="hibernate.c3p0.timeout">5000</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="hibernate.c3p0.validate">false</property>

其中hibernate.c3p0.timeout属性指定多少秒后连接超时,连接池会自动对超时连接进行重查。

转载于:https://my.oschina.net/zchuanzhao/blog/787777

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值