hibernateutil.java

来自「运用hibernate技术 实现的留言板」· Java 代码 · 共 56 行

JAVA
56
字号
/**
 * 
 */
package com.tiandinet.hibernate;

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

import org.apache.log4j.Logger;

import java.lang.ThreadLocal;

/**
 * Hibernate session function.
 * @author Meng Yang
 * @value 1.0.1
 */
public class HibernateUtil {
	private static Logger log = Logger.getLogger(HibernateUtil.class);

	private static final SessionFactory sessionFactory;
	static {
		try {
			// Create the SessionFactory
			sessionFactory = new Configuration().configure().buildSessionFactory();
		} catch (Throwable ex) {
			// Make sure you log the exception, as it might be swallowed
			log.error("Initial SessionFactory creation failed.", ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static final ThreadLocal sessionHolder = new ThreadLocal();

	public static Session getSession() throws HibernateException {
		Session s = (Session) sessionHolder.get();
		// Open a new Session, if this Thread has none yet
		if (s == null) {
			s = sessionFactory.openSession();
			sessionHolder.set(s);
		}
		return s;
	}

	public static void closeSession() throws HibernateException {
		Session s = (Session) sessionHolder.get();
		//just for 1.5
		//sessionHolder.remove();
		sessionHolder.set(null);
		
		if (s != null)
			s.close();
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?