问题描述
Hibernate与MySQL的连接我的db没有关闭。在10秒内点击10次,我得到这个连接统计从MySQL Workbench(在我的开发机器,我是唯一的用户)。
我有这些
Hibernate connections to MySQL my db are not closing. After clicking 10 times in like 10 second, I get this connection statistics from MySQL Workbench (in my development machine. I'm the only user).MySQL Workbench Server Status
I have those in place
- C3P0并运行(从log4j检查,没有与C3P0相关的问题,似乎正在运行)
- 一个ServletReqestListener检查是否有打开的会话并关闭
- Hibernate Session对象保存在ThreadLocal中,因此每个请求只有一个连接,它在第一次查询时打开,并在ServletRequestListener中关闭。
- 每次我打开一个会话并关闭一个会话,我输出Session Opened和Session Closed到System.out,如代码示例中所示。在每个请求,每个页面刷新,我获得会话已打开和会话关闭后,。所以我的小逻辑工作。但连接未关闭。
- C3P0 and running (checked from log4j, no problem related to C3P0 and seems running)
- A ServletReqestListener which checks if there's an open session and closes it in requestDestroyed() method.
- Hibernate Session object is being kept in ThreadLocal, so every request only have one connection, which opens at first query, and closes in ServletRequestListener.
- Every time I open a session and close a session I output "Session Opened" and "Session Closed" to System.out as in the code example blow. At every request, every page refresh, I get "Session Opened" and after "Session Closed", repectively. So my little logic works. But the connection does not get closed.
我的hibernate.cfg.xml
$ b
My 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 -->
我每次要关闭会话时调用的代码块。 strong>
The code-block I call in everytime where I want to close the session.
if (session == null)
return;
if (session.isOpen()) {
if (session.isDirty())
session.flush();
session.close();
System.out.println("Session closed");
}
我错过了什么吗?
推荐答案
好吧,它似乎我每次创建SessionFactory。这里有一个很好的类在链接,使SessionFactory静态解决问题。
Well it seems I was creating SessionFactory everytime. There's a nice class here at the link, making SessionFactory static solved the problem. http://docs.jboss.org/hibernate/core/3.3/reference/en/html/tutorial.html#tutorial-firstapp-helpers
这篇关于Hibernate连接即使使用C3P0 +显式也不关闭session.close()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!