我有一个包含休眠的Tomcat Servlet.它正常工作.当servlet启动时,我将初始化休眠状态并创建一个会话工厂.然后,当执行各种数据库事务时,我将使用该会话工厂来生成会话.到现在为止还挺好.我的问题出在servlet长时间不活动之后(例如,当用户晚上回家然后第二天早上尝试登录时).突然,我无法与数据库进行通信.在日志中,我看到了
org.hibernate.exception.JDBCConectionException:无法执行查询.
如果停止并重新启动Tomcat,重新初始化servlet并重建会话工厂,则一切正常.这几乎就像会话工厂本身正在超时吗?
有任何想法吗?
谢谢,
艾略特
解决方法:
If I stop and restart Tomcat, reinitializing my servlet and rebuilding my session factory, everything works fine. It is almost like the session factory itself is timing out?
它不是会话工厂,而是会话工厂使用的连接(例如,众所周知,默认情况下,MySQL在闲置8小时后会超时连接).要么:
>使用一个连接池,该池能够验证借用的连接并更新它们〜或〜
>增加数据库端的空闲超时
OK. Suppose I use a c3P0 connection pool. How do I specify in the hibernate.cfg.xml file that I want to “validate connections on borrow” or does it do this by default?
Configuring Connection Testing中记录了使用C3P0时的各种选项.我的建议是使用idleConnectionTestPeriod
参数:
The most reliable time to test
Connections is on check-out. But this
is also the most costly choice from a
client-performance perspective. Most
applications should work quite
reliably using a combination ofidleConnectionTestPeriod
andtestConnectionsOnCheckIn
. Both the
idle test and the check-in test are
performed asynchronously, which leads
to better performance, both perceived
and actual.Note that for many applications, high
performance is more important than the
risk of an occasional database
exception. In its default
configuration, c3p0 does no Connection
testing at all. Setting a fairly longidleConnectionTestPeriod
, and not
testing on checkout and check-in at
all is an excellent, high-performance
approach.
要使用休眠配置C3P0,请确保阅读the relevant instructions(并使用适当的属性和适当的文件).