Ram
Ram

Reputation: 233

Hibernate not closing connection

I am using Hibernate + jersey Rest And Mysql as backend for database. In Hibernate used cp3 pool for connection but after some time it creates so many idle connections and gets stuck. my configurations are :

enter image description here enter image description here

package com.appname.hibernate.util;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
private static SessionFactory sessionFactory;

static {
    try {
        Configuration configuration = new Configuration().configure();

        sessionFactory = configuration.buildSessionFactory();
    } catch (HibernateException he) {
        System.err.println("Error creating Session: " + he);
        he.printStackTrace();
        throw new ExceptionInInitializerError(he);
    }
}

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}
}
////////////////////// INSIDE DAO ///////////////////////////

private Session getSession() {

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session;
try {
    session = sessionFactory.getCurrentSession();
} catch (org.hibernate.HibernateException he) {
    session = sessionFactory.openSession();
}
return session;
}

public Users regsiterUser(Users users) throws Exception {

Session session = null;

try {
session = getSession();
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(users);
transaction.commit();
return users;

//Using context session that is why I am not closing session
} catch (Exception e) { throw e; }
}

I am calling this DAO function form my controller where I am making transaction and session inside DAO layer. Please help me I am trying to solve this but not getting any solution please have a look what is wrong with the above configuration and code ......

Thanks in advance.....

Upvotes: 4

Views: 10170

Answers (1)

Luca Basso Ricci
Luca Basso Ricci

Reputation: 18403

I think this session = sessionFactory.openSession(); should be closed manually after use because it is not managed by an orchestrator that release resource after use.

Upvotes: 2

Related Questions