hibernate 获取 SessionFactory 的工具类

版权声明:尊重原创,转载请标明出处 https://blog.csdn.net/jifgjifg/article/details/52314881
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // 从 hibernate.cfg.xml 创建 SessionFactory
            return new Configuration().configure().buildSessionFactory();

        } catch (Throwable ex) {
            // 创建 SessionFactory 失败时输出错误
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // 关闭 caches 和 connection pools
        getSessionFactory().close();
    }
}

猜你喜欢

转载自blog.csdn.net/jifgjifg/article/details/52314881