package util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static ThreadLocal<Session> threadlocal = new ThreadLocal<Session>() ;
private static SessionFactory sessionFactory;
static{
buildFactory();
}
public static Session getSession(){
Session session = threadlocal.get() ;
if( session == null || !session.isOpen() ){
if( sessionFactory == null ){
buildFactory();
}
session = sessionFactory.openSession() ;
threadlocal.set(session);
}
return session ;
}
public static void closeSession(){
Session session = threadlocal.get() ;
threadlocal.set(null);
if( session != null && session.isOpen()){
session.close() ;
}
}
private static void buildFactory(){
sessionFactory = new Configuration().configure(CONFIG_FILE_LOCATION).buildSessionFactory() ;
}
}
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static ThreadLocal<Session> threadlocal = new ThreadLocal<Session>() ;
private static SessionFactory sessionFactory;
static{
buildFactory();
}
public static Session getSession(){
Session session = threadlocal.get() ;
if( session == null || !session.isOpen() ){
if( sessionFactory == null ){
buildFactory();
}
session = sessionFactory.openSession() ;
threadlocal.set(session);
}
return session ;
}
public static void closeSession(){
Session session = threadlocal.get() ;
threadlocal.set(null);
if( session != null && session.isOpen()){
session.close() ;
}
}
private static void buildFactory(){
sessionFactory = new Configuration().configure(CONFIG_FILE_LOCATION).buildSessionFactory() ;
}
}