如果每次操作数据都开启一次session是不是太浪费了。由此、写了下当前请求也就是当前线程范围使用的Session。
直接上代码了、不知道是不是有什么问题没注意到?有的话请指正。
package com.oa.hibernate.utils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
*
* @author:zll
* 2012-3-28 上午07:24:00
* description:当前线程(请求)范围的Session工具类
*/
public class HibernateSessionUtil {
private static final String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static String configFile = CONFIG_FILE_LOCATION;
private static SessionFactory sf = null;
//当前线程相关的session
private static final ThreadLocal<Session> localSession = new ThreadLocal<Session>(){
protected Session initialValue() {
return sf.openSession();
};
};
private HibernateSessionUtil() {
}
static{
try {
//采用默认的设置
sf = new Configuration().configure(configFile).buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 得到当前的session
* @return
*/
public static Session getCurrentSession(){
Session session = localSession.get();
if (session ==null || !session.isOpen()) {
if (sf == null) {
rebuildSessionFactory();
}
session = (sf!=null)? sf.openSession():null;
localSession.set(session);
}
return session;
}
/**
* 重新加载SessionFactory
*
*/
public static void rebuildSessionFactory() {
try {
sf = new Configuration().configure(configFile).buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* 关闭当前的session
*
* @throws HibernateException
*/
public static void closeCurrentSession() {
Session session =localSession.get();
localSession.set(null);
if (session != null && session.isOpen()) {
session.close();
}
}
/**
* 返回SessionFactory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sf;
}
/**
* 设置config路径 SessionFactory将在下次重新加载
* @param configFile
*/
public static void setConfigFile(String configFile){
HibernateSessionUtil.configFile = configFile;
sf = null;
}
}