Seregwethrin
Seregwethrin

Reputation: 1389

Hibernate connections are not closed even with C3P0 + explicit session.close()

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

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 -->

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

Do I miss something?

Upvotes: 5

Views: 16725

Answers (2)

Seregwethrin
Seregwethrin

Reputation: 1389

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

Upvotes: 5

Nurlan
Nurlan

Reputation: 673

private static final ThreadLocal<Session> session = new ThreadLocal<Session>();

public static void closeSession() throws HibernateException {
    Session s = session.get();
    if (s != null) {
        s.close();
        session.remove();
    }
}

actually I am doing like this and it works

Upvotes: 1

Related Questions