import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateOperation {
public static final SessionFactory sessionFactory;
static {
try{
// 采用默认的设置,即是到web-INF的classes目录下去找hibernate.cfg.xml文件
sessionFactory=new Configuration().configure().buildSessionFactory();
}catch(Throwable ex){
System.err.println("Inital SessionFactory creation failed."+ex);
throw new ExceptionInInitializerError(ex);
}
}
//Session 对象时不安全的,需要将它与一个ThreadLocal实例绑定,以保证其线程的安全
public static final ThreadLocal session=new ThreadLocal();
public static Session currenSession() throws HibernateException{
Session s=(Session)session.get();
if(s==null){
s=sessionFactory.openSession();
}
return s;
}
public static void closeSession() throws HibernateException{
Session s=(Session)session.get();
if(s!=null){
s.close();
session.set(null);
}
}
}
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateOperation {
public static final SessionFactory sessionFactory;
static {
try{
// 采用默认的设置,即是到web-INF的classes目录下去找hibernate.cfg.xml文件
sessionFactory=new Configuration().configure().buildSessionFactory();
}catch(Throwable ex){
System.err.println("Inital SessionFactory creation failed."+ex);
throw new ExceptionInInitializerError(ex);
}
}
//Session 对象时不安全的,需要将它与一个ThreadLocal实例绑定,以保证其线程的安全
public static final ThreadLocal session=new ThreadLocal();
public static Session currenSession() throws HibernateException{
Session s=(Session)session.get();
if(s==null){
s=sessionFactory.openSession();
}
return s;
}
public static void closeSession() throws HibernateException{
Session s=(Session)session.get();
if(s!=null){
s.close();
session.set(null);
}
}
}