如何防止Hibernate + c3p0 + MySql创建大量睡眠连接?

Bra*_*cey 4 java mysql gwt hibernate c3p0

我正在使用GWT与Hibernate,c3p0和MySQL来制作一个受众有限的网络应用程序(每天最多50个用户).在测试期间,我发现Hibernate正在打开与每个会话的连接但不关闭它,无论使用何种close()方法.

我目前的配置如下:

hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=
hibernate.connection.username=
hibernate.connection.password=
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.current_session_context_class=thread
hibernate.c3p0.min_size=1
hibernate.c3p0.max_size=1
hibernate.c3p0.timeout=10
hibernate.c3p0.max_statements=50
hibernate.c3p0.idle_test_period=10
hibernate.c3p0.unreturned_connection_timeout=1
hibernate.connection.provider_class=org.hibernate.connection.C3P0ConnectionProvider
Run Code Online (Sandbox Code Playgroud)

每次与应用程序的新连接都会创建一个新池.例如,如果我将池大小设置为3,则应用程序的2个连接将导致6个连接,直到应用程序关闭.

预期的行为是在每次事务之后简单地关闭或重用连接.我怎样才能做到这一点?

Pas*_*ent 7

在测试期间,我发现Hibernate正在打开与每个会话的连接但不关闭它,无论使用close()方法

使用连接池时,调用Connection#close()不会物理关闭连接,而是将其返回到池中以供将来重用.换句话说,连接保持打开状态,这是使用池的重点.


我调用以下内容:AnnotationConfiguration().buildSessionFactory().getCurrentSession();

嗯,这就是问题所在.您正在创建一个SessionFactory遍历(每个创建自己的池),而您应该在应用程序的生命周期中创建一次.如果您没有使用任何特定框架,这通常在某个实用程序类(着名HibernateUtil类)中完成.

官方的Hibernate教程有一个非常基本的例子.或者看看这个更富有的.