我是彻底疯了,java.lang.RuntimeException: Session is closed!
java.lang.RuntimeException: Session is closed!
这到底怎么回事,第一次可以,但第二次马上就爆这个错误!!!
package com.sina.util;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
final public class HibernateUtil {
private static SessionFactory sessionFactory=null;
//用ThreadLocal模式 (线程局部变量模式) 管理Session
private static ThreadLocal threadLocal=new ThreadLocal();
private HibernateUtil(){};
static {
sessionFactory=new Configuration().configure().buildSessionFactory();
}
public static Session openSession(){
return sessionFactory.openSession();
}
public static Session getCurrentSession(){
Session session=(Session) threadLocal.get();
if(session==null){
session=sessionFactory.openSession();
//把session对象设置到threadLocal,相当于session和线程已经绑定
threadLocal.set(session);
}
return session;
}
//提供统一的查询方法
public static List executeQuery (String hql){
Session session=null;
Transaction ts=null;
List list=null;
try{
session=HibernateUtil.getCurrentSession();
ts=session.beginTransaction();
list=session.createQuery(hql).list();
ts.commit();
}catch (Exception e) {
// TODO: handle exception
if (ts!=null) {
ts.rollback();
}
throw new RuntimeException(e.getMessage());
}finally{
if (session!=null && session.isOpen()) {
session.close();
}
}
return list;
}
}