HibernateUtil

单例模式得到sessionfactory
package com.riverstone.biz.impl;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

public class HibernateUtil {
	private HibernateUtil() {
	}
	private static final String HIBERNATE_CONFIG_FILE = "/hibernate.cfg.xml";

	private static SessionFactory sessionFactory;
	static {
		try {
			// 读取配置文件
			Configuration configuration = new Configuration()
					.configure(HIBERNATE_CONFIG_FILE);
			// 获取SessionFactory
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * 关闭连接
	 */

	public static void closeSession(Session session) {
		if (session != null) {
			if(session.isOpen()){
				session.close();
			}
		}
	}
}

你可能感兴趣的:(Hibernate)