我有一个包含 hibernate 功能的 Tomcat servlet。它正常工作。当 servlet 启动时,我初始化 hibernate 并创建一个 session 工厂。然后我使用这个 session 工厂在执行各种数据库事务时生成 session 。到目前为止,一切都很好。我的问题是在 servlet 长时间不活动之后出现的(比如当用户晚上回家然后第二天早上尝试登录时)。突然,我无法与数据库通信。在我看到的日志中
org.hibernate.exception.JDBCConectionException:无法执行查询。
如果我停止并重新启动 Tomcat,重新初始化我的 servlet 并重建我的 session 工厂,一切正常。这几乎就像 session 工厂本身正在超时?
有什么想法吗?
谢谢,
埃利奥特
最佳答案
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?
它不是 session 工厂,而是 session 工厂使用的连接(例如,众所周知,默认情况下,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?
使用 C3P0 时的各种选项记录在 Configuring Connection Testing 中.我的建议是使用 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 of
idleConnectionTestPeriod
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 long
idleConnectionTestPeriod
, and not testing on checkout and check-in at all is an excellent, high-performance approach.
要使用 Hibernate 配置 C3P0,请务必阅读 the relevant instructions (并使用适当的属性和适当的文件)。
关于java - servlet 的 Hibernate 超时问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3983674/