HibernateUtil工具类

package com.it.util;

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

/**
 * Hibernate工具类
 */
public class HibernateUtil {
	private static final Configuration config = new Configuration().configure();
	private static final SessionFactory factory = config.buildSessionFactory();
	//本地线程对象
	private static ThreadLocal<Session> local = new ThreadLocal<Session>();
	
	/*
	 * 获取session
	 */
	public static Session getSession(){
		Session session = local.get();
		if(session == null){
			session = factory.openSession();
			local.set(session);
		}
		return session;
	}
	
	/*
	 * 关闭
	 */
	public static void closeSession(){
		Session session = local.get();
		if(session != null && session.isOpen()){
			session.close();
			session = null;
		}
		local.set(null);
	}
}

posted on 2016-05-28 18:29  菜鸟Z  阅读(154)  评论(0编辑  收藏  举报

导航