dbutil.java

来自「J2EE SSH 的一个例子」· Java 代码 · 共 53 行

JAVA
53
字号
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 + =
减小字号Ctrl + -
显示快捷键?