Hibernate用Mysql数据库时链接关闭异常的解决

前一段时间朋友用hibernate+mysql整了一个应用,出现tomcat放一夜,mysql连接出现错误的情况,具体的错误信息忘记了。

在网上查找一下,找到了这个帖子,还有就是这个了;原来Mysql在经过8小时不使用后会自动关闭已打开的连接,摘录原文如下:

5.4.

I have a servlet/application that works fine for a day, and then stops working overnight

MySQL closes connections after 8 hours of inactivity. You either need to use a connection pool that handles stale connections or use the "autoReconnect" parameter (see "Developing Applications with MySQL Connector/J").

Also, you should be catching SQLExceptions in your application and dealing with them, rather than propagating them all the way until your application exits, this is just good programming practice. MySQL Connector/J will set the SQLState (see java.sql.SQLException.getSQLState() in your APIDOCS) to "08S01" when it encounters network-connectivity issues during the processing of a query. Your application code should then attempt to re-connect to MySQL at this point.

现把具体方法贴出来,以供大家共享.
方法一:
               设置你的MYSQL数据库:wait_timeout=24*60*60<秒>,把它的值设置大一点,呵呵
 方法二:
               配置Hibernate C3p0连接池,配置如下:
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
   <property name="c3p0.max_size">20</property>
   <property name="c3p0.min_size">5</property>
   <property name="c3p0.timeout">20</property>
   <property name="c3p0.max_statements">100</property>
   <property name="c3p0.idle_test_period">120</property>
   <property name="c3p0.acquire_increment">2</property>

注意这里标红的部分,要设置c3p0.timeout的值小于MySql的wait_timeout的值,这样才行,要不还会出现异常.

这次是一个教训,所以不论从稳定还是性能的考虑,都应该选择相对更加成熟的连接池。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值