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

时间:2022-09-19 23:39:55

解决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属性指定多少秒后连接超时,连接池会自动对超时连接进行重查。