java - servlet 的 Hibernate 超时问题

标签 java database hibernate servlets

我有一个包含 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 and testConnectionsOnCheckIn. 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/

相关文章:

java - 当我启动进程时我的 Jframe 卡住

sql - 我将如何在 SQL 的 case 语句中使用 datename

java - 如何使用里面包含OR条件的AND SqlRestriction?

java - Hibernate 中集合未正确加载

hibernate - Gorm返回值类型

java - C 与 Java 中的内存分配

java - WindowBuilder 不兼容的 Java 版本

java - 在Eclipse中的Hadoop Mapreduce中将命令行选项传递给reducer

mysql - 如何修复插入许多重复行的 INSERT INTO ... SELECT 代码?

sql-server - 博客应用程序的最佳数据库(关系型 - SQL 与 NoSQL)