⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 hibernateutil.java

📁 运用hibernate技术 实现的留言板
💻 JAVA
字号:
/**
 * 
 */
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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -