简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM