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

📄 hibernateutil.java

📁 博克后台的开发,有很多使用的方法和例子可以提供给大家学习
💻 JAVA
字号:
/*
 * description: 对sessionFactory的初始化设置与使用;从SessionFactory获取一个Hibernate的工作单元session。
 * 
 * Created on 2005-7-4
 * @author WuQiaoYun
 * 
 * Modified on
 */

package com.common.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
 * 对sessionFactory的初始化设置与使用;从SessionFactory获取一个Hibernate的工作单元session。
 * @author WuQiaoYun
 */
public class HibernateUtil {
    /**
     * sessionFactory对象
     */
	public static final SessionFactory sessionFactory;
	/**
	 * 静态块,初始化sessionFactory
	 */
	static {
	    try {
	    	sessionFactory=new Configuration().configure().buildSessionFactory(); 
	    }catch(Throwable te) {
	    	System.err.println("Initial SessionFactory creation failed."+te);
	    	throw new ExceptionInInitializerError(te);
	    }	
	}
   /**
    * 初始化ThreadLocal对象
    */
	public static final ThreadLocal session = new ThreadLocal();
	
	 /**
	  * function:获取一个当前的hibernate的工作单元session,并返回
	  *
	  * @return Session 返回hibernate的工作单元session
	  */
	public static Session currentSession() throws HibernateException{
		Session s = (Session)session.get();
		if (s==null) {
		   s = sessionFactory.openSession();
		   session.set(s);
		}
	    return s;
	}

	/**
	 * function: close 当前的hibernate的工作单元session
	 * 
	 * @throws HibernateException
	 */	
	public static void closeSession() throws HibernateException{
		Session s = (Session)session.get();
		if (s!=null) {
		   s.close();	
		}
		session.set(null);
	}
}

⌨️ 快捷键说明

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