hibernate3.x版本
package hibernate_01; import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; public class hibernateUtils {
private static Configuration cfg = null;
private static SessionFactory sessionFactory = null;
private static Session session = null;
static{
cfg = new Configuration().configure();
sessionFactory = cfg.buildSessionFactory();
}
public static Session getSession(){
if(sessionFactory!=null){
session = sessionFactory.openSession();
}else{
sessionFactory = cfg.buildSessionFactory();
}
return session = sessionFactory.openSession();
}
public static void closeSession(){
if(session != null && session.isOpen()){
session.close();
}
}
}
hibernate4.x
package cn.siggy.util; import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration; public class HibernateUtil {
private static Configuration cfg=null;
private static SessionFactory factory=null;
private static Session session = null;
static{
cfg = new Configuration().configure();
factory = cfg.buildSessionFactory(new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build());
}
public static Session getSession(){
if(factory!=null)
return factory.openSession();
factory=cfg.buildSessionFactory(new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build());
return session = factory.openSession();
}
public static void closeSession(){
if(session!=null&&session.isOpen())
session.close();
}
}