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

📄 hibernateutil.java

📁 hibernate源代码使用 J2EE项目开发
💻 JAVA
字号:
package com.utils;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	private static Logger log = Logger.getLogger(HibernateUtil.class);
	private static final SessionFactory sessionFactory;
	static {
		try{
			sessionFactory = new Configuration().configure().buildSessionFactory();
		//}catch(Exception e){
		}catch(Throwable e){
			log.error(e);
			throw new ExceptionInInitializerError(e);
		}
	}
	
	/**
	  使用ThreadLocal可以有效隔离执行所使用的数据,所以避开了Session的多线程之间的数据共享问题。
	  使用ThreadLocal thread_var=new ThreadLocal()语句生成的变量是一个只在当前线程有效的
	 变量,也就是说不同线程所拥有的thread_var变量是不一样的。在这个变量内可以用set(object)方
	 法放置保存一个对象,只要这个线程没有结束,都可以通过thread_var变量的get方法取出原先放入的
	 对象。
	 */
	private static final ThreadLocal thread_var = new ThreadLocal();
	
	public static Session currentSession(){
		Session s = (Session)thread_var.get();
		if (s==null){
			s = sessionFactory.openSession();
			thread_var.set(s);//very important
		}
		return s;
	}
	
	public static void closeSession(){
		Session s = (Session)thread_var.get();
		if (s!=null){
			s.close();
		}
		thread_var.set(null);
	}
	
	public static void main(String[] args){
		System.out.println(HibernateUtil.currentSession());
		HibernateUtil.closeSession();
	}
}

⌨️ 快捷键说明

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