Mohamed Nagy
Mohamed Nagy

Reputation: 176

Hibernate : Change Hibernate Connection

Is there a way I can make my connection to the database in Hibernate to be per-session not per-request? Because I have noticed that for every request to in of my pages in the web App the Hibernate Configuration is re-created, and that might affect the performance.

Upvotes: 0

Views: 117

Answers (1)

Y. Tarion
Y. Tarion

Reputation: 423

You should keep the same SessionFactory without recreating one. So you need to make it static.

Example :

public class HibernateUtils{
    private static SessionFactory session;

    private static void createSession(){
        sessionFactory = new Configuration().configure().buildSessionFactory();
    }
    public static Session getSession(){
         if(session == null)
             createSession()
         return session.openSession();
    }
}

When you will call "HibernateUtils.getSession()" that will create your session only if it isn't exist

Of course, you need to close session when needed

Upvotes: 1

Related Questions