HibernateSessionFactory演示样例

时间:2023-03-10 05:13:42
HibernateSessionFactory演示样例

package common;



import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;



public class HibernateSessionFactory {

    private static Configuration cfg;

    private static SessionFactory sessionFactory;

    

    private HibernateSessionFactory() {}

    

    static {

        try {

            cfg = new Configuration().configure();

            sessionFactory = cfg.buildSessionFactory();

        } catch (HibernateException e) {

            // 做日志

            throw new RuntimeException("hibernate初始化错误", e);

        }

    }

    

    public static Session getSession() {

        return sessionFactory.getCurrentSession();

//        return sessionFactory.openSession();

    }

}