环境:Hibernate4.2+Mysql5.0
原因:mysql默认对所有连接的有效时间为28800秒,正好8小时,也就是说,8小时内,这个连接没有请求和响应,mysql将自动断开该连接,但是,此时Hibernate的连接池并不知道这个连接已经被断开,如果,此时,有线程需要使用这个连接的时候,就会报StackTrace:org.hibernate.exception.JDBCConnectionException: Could not open connection。
解决方案:
1.重启tomcat。
2.增大MySQL的连接有效时间
2.1 直接修改mysql的my.ini文件,wait_timeout最大为31536000即1年,在my.ini中加入:
[mysqld]
wait_timeout=31536000
interactive_timeout=31536000
2.2 创建连接时,通过在getSession方法中执行session.createSQLQuery("set global wait_timeout=60").executeUpdate();可以灵活设置连接有效时间,且解决代码部署后需配置mysql的问题。
3.网上查到的在jdbc的connection url后加入参数: autoReconnect=true 或者在hibernate的配置文件hbm.cfg.xml加入
<property name=”connection.autoReconnect”>true</property>
<property name=”connection.autoReconnectForPools”>true</property>
<property name=”connection.is-connection-validation-required”>true</property>
4.不用Hibernate默认的连接池,使用C3P0连接池
最后使用4解决问题。配置C3P0所需jar包链接:http://pan.baidu.com/s/1o6WSsHW
参考的其他文章:http://blog.youkuaiyun.com/nethibernate/article/details/6658855
http://blog.youkuaiyun.com/lanmo555/article/details/37659341
http://www.2cto.com/database/201209/158448.html
http://blog.youkuaiyun.com/a79412906/article/details/8971534