简体   繁体   中英

What are the required C3P0 settings for Hibernate?

I use Hibernate 4.3.0 together with MySQL and Tomcat. All required libraries are in classpath and here's a hibernate.cfg.xml :

<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">false</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.connection.autocommit">false</property>
<property name="current_session_context_class">thread</property>

<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>

<!-- Disable the second-level cache  -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.timeout">3000</property>
<property name="hibernate.c3p0.idle_test_period">300</property>

With the above settings, after 20 connections to database application is not connecting anymore, and I did't find in application logs relating info to this behaviour.

Does anyone knows what is wrong, and how I can setup c3p0 and hibernate correctly?

The settings are fine. The reason for running out of connections is because connections are not properly released.

Make sure you:

  • commit the transaction on success
  • rollback transaction on failure
  • close your Hibernate session after you're done with it:

So, this is how you should operate a Hibernate session, in case you don't have Spring to handle transaction/session management on your behalf:

Session session = factory.openSession();
Transaction tx = null;
try {
   tx = session.beginTransaction();       
   ...
   tx.commit();
}
catch (Exception e) {
   if (tx!=null) tx.rollback(); 
}finally {
   session.close();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM