andy007
andy007

Reputation: 917

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?

Upvotes: 1

Views: 462

Answers (1)

Vlad Mihalcea
Vlad Mihalcea

Reputation: 153690

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();
}

Upvotes: 2

Related Questions