---
title: "hibernate管理session的例子"
author: "wenlong342"
date: "2008-03-06T15:34:49Z"
tags: ["Hibernate"]
slug: "hibernate-session"
draft: false
lastmod: "2008-03-06T15:34:49Z"
id: 168789
url: "https://wenlong.iteye.com/blog/168789"
---

package com.sict.employeeManagement.help;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	    public static SessionFactory getSessionFactory() {
	        return _instance._sessionFactory;
	    }
		public static void closeSession(Session session) {
			try {
				if ((session != null) && (session.isOpen())) {
					session.close();
				}
			}
			catch (HibernateException he) {
				he.printStackTrace();
			}
		}
		public static Session openSession() throws HibernateException {
			return openSession(getSessionFactory());
		}

		public static Session openSession(SessionFactory sessionFactory)
			throws HibernateException {

			return _instance._sessionFactory.getCurrentSession();
		}
		private HibernateUtil() {
	        try {
				Configuration configuration = new Configuration();
				configuration = configuration.configure();
				_sessionFactory = configuration.buildSessionFactory();
	        }
			catch (Exception e) {
				e.printStackTrace();
	        }
		}
		private static HibernateUtil _instance = new HibernateUtil();
		private SessionFactory _sessionFactory;
}
