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

📄 hibernateutilplus.java

📁 首先确保MySQL4.0数据库已经正确安装
💻 JAVA
字号:
package edu.jnestore.util;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;

/**
 * HibernateUtilPlus用来获取Hiberante 的Session对象
 */
public class HibernateUtilPlus {

	private static SessionFactory sessionFactory = null;
	public static final ThreadLocal session = new ThreadLocal();
        //获取Hibernate的Session对象
	public static Session currentSession() throws HibernateException {
		if (sessionFactory == null) {
			// 如果sessionFactory实例为null则从JNDI中获取
			if (getSystemSessionFactory() == false) {
				throw new HibernateException("Exception geting SessionFactory from JNDI ");
			}
		}
		Session s = (Session) session.get();
		// 如果当前线程还没有获得session对象,则通过sessionFactory获得一个
		if (s == null) {
			s = sessionFactory.openSession();
			session.set(s);
		}
		return s;
	}
        //关闭Session
	public static void closeSession() throws HibernateException {
		Session s = (Session) session.get();
		session.set(null);
		if (s != null)
			s.close();
	}
	//获得SessionFactory对象
	private static boolean getSystemSessionFactory() {
		try {
			//从JNDI中取得SessionFactory的实例,如果出错返回false
			Context inttex = new InitialContext();
			sessionFactory =
				(SessionFactory) inttex.lookup("HibernateSessionFactory");
		} catch (NamingException e) {
			return false;
		}
		return true;
	}
}

⌨️ 快捷键说明

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