java - 即使使用 C3P0 + 显式 session.close() 也不会关闭 Hibernate 连接

标签 java hibernate connection connection-pooling connection-close

与我的数据库的 MySQL 的 Hibernate 连接没有关闭。在大约 10 秒内单击 10 次后,我从 MySQL Workbench(在我的开发机器上。我是唯一的用户)获得了这个连接统计信息。 MySQL Workbench Server Status

我已经准备好了

  • C3P0 并正在运行(从 log4j 检查,没有与 C3P0 相关的问题并且似乎正在运行)
  • 一个 ServletReqestListener,它检查是否有打开的 session 并在 requestDestroyed() 方法中关闭它。
  • Hibernate Session 对象保存在 ThreadLocal 中,因此每个请求只有一个连接,该连接在第一次查询时打开,并在 ServletRequestListener 中关闭。
  • 每次打开 session 和关闭 session 时,我都会将“ session 已打开”和“ session 已关闭”输出到 System.out,如代码示例中所示。在每次请求时,每次页面刷新时,我分别得到“ session 打开”和“ session 关闭”之后。所以我的小逻辑起作用了。但是连接不会关闭。

我的 hibernate.cfg.xml

<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">officenic</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/officenic</property>
<property name="hibernate.connection.username">officenic</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

<!-- configuration pool via c3p0 -->
<property name="hibernate.c3p0.acquire_increment">1</property>
<property name="hibernate.c3p0.idle_test_period">100</property> <!-- seconds -->
<property name="hibernate.c3p0.max_size">5</property>
<property name="hibernate.c3p0.max_statements">0</property>
<property name="hibernate.c3p0.min_size">1</property>
<property name="hibernate.c3p0.timeout">100</property> <!-- seconds -->

每次我想关闭 session 时调用的代码块。

if (session == null)
    return;

if (session.isOpen()) {

      if (session.isDirty())
         session.flush();

    session.close();
    System.out.println("Session closed");
}

我错过了什么吗?

最佳答案

好吧,我似乎每次都在创建 SessionFactory。链接上有一个很好的类,使 SessionFactory 静态解决了这个问题。 http://docs.jboss.org/hibernate/core/3.3/reference/en/html/tutorial.html#tutorial-firstapp-helpers

关于java - 即使使用 C3P0 + 显式 session.close() 也不会关闭 Hibernate 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9755523/

相关文章:

java - 即使设置 Soot 库类路径,接收也找不到类错误

java - 数组中的重复值

MySQL默认最大连接数

java - 集群环境下的Hibernate ORM

Java 7 J颜色选择器 : Disable Transparency Slider

java - 我怎样才能找出是什么让我的 WAR 在 Tomcat 上部署了这么长时间?

hibernate - 当嵌套层次结构中可用时,相同的对象将作为 Lazy 获取

集合表的 hibernate 条件查询?

azure - 从外部访问 Azure 云上的 Cassandra Node

java - 为什么 Clob 的创建与 Connection 类相关联?