Control the hibernate session(when to close it manually)

前端 未结 4 653
后悔当初
后悔当初 2020-12-04 06:43

I am new in hibernate,after read the hibernate api and tutorial,it seems that the session should closed when not used.

Like this:

Session sess=getSe         


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 06:48

    We can make use of ThreadLocal.

    public class MyUtil {
    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;
    private static final ThreadLocal threadLocal;
    
    static {
    try {
        Configuration configuration = new Configuration();
        configuration.configure();
        serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        threadLocal = new ThreadLocal();
    
        } catch(Throwable t){
          t.printStackTrace();
          throw new ExceptionInInitializerError(t);
        }
    }
    public static Session getSession() {
        Session session = threadLocal.get();
        if(session == null){
            session = sessionFactory.openSession();
            threadLocal.set(session);
        }
        return session;
    }
    
    public static void closeSession() {
        Session session = threadLocal.get();
        if(session != null){
        session.close();
        threadLocal.set(null);
        }
    }
    
    public static void closeSessionFactory() {
        sessionFactory.close();
        StandardServiceRegistryBuilder.destroy(serviceRegistry);
       }
    }
    

    Here, the SessionFactory is initialized only once using the static block. Hence, whenever the main class makes a call to getSession(), the presence of Session object is first checked in the threadLocal object. Therefore, this program provides thread-safety. After each operation, closeSession() will close the session and set the threadLocal object to null. Finally call the closeSessionFactory().

提交回复
热议问题