Sri Sri - 5 months ago 30
Java Question

Where to open and where to close SessionFactory in my Application

I am developing jsf application and using hibernate as back end. I want create session factory and close it once through out application. I am creating Session factory with util class.

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil
{
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

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

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

public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
}

public static void closeFactory() {
if (sessionFactory != null) {
try {
sessionFactory.close();
} catch (HibernateException ignored) {
log.error("Couldn't close SessionFactory", ignored);
}
}
}


In my every method of DAO classes I am opening session factory and closing it. So where i can open/close the session factory only once for application.
Thanks in advance.

Answer

Where to open and where to close SessionFactory in my Application

You are using singleton sessiong facoty object. So You can call the getSessionFactory() method with class name. So that you need not to create object for session factory every time. Your DAO class methods should like this

Method in DAO class

public boolean createUser(NewUserDTO newUserDTO) {
    try {
        sessionFactory = DBUtils.getSessionFactory();
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();
        session.save(newUserDTO);
        session.getTransaction().commit();
    } catch (RuntimeException runtimeException) {
        LOGGER.error(runtimeException);
        transaction.rollback();
        return false;
    } finally {
        if (session != null) {
            session.close();
        }
    }
    return true;
}

And session must be closed for every method. So that you are not creating session factory for every class.

Comments