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

📄 dbutil.java

📁 J2EE SSH 的一个例子
💻 JAVA
字号:
package com.huangdong.dbwebdemo;

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;

/**
 * @author HD
 */
public class DBUtil {

	private static SessionFactory sessionFactory = null;
	public static final ThreadLocal session = new ThreadLocal();

	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();
		if (s == null) {
			s = sessionFactory.openSession();
			session.set(s);
		}
		return s;
	}

	public static void closeSession() throws HibernateException {
		Session s = (Session) session.get();
		session.set(null);
		if (s != null)
			s.close();
	}
	
	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 + -