单例模式:
SessionFactory是重量级的,一般情况下,一个项目通常只需要一个SessionFactory就够(单例模式),当需要操作多个数据库时,可以为每个数据库指定一个SessionFactory。
- 在dao包下,新建HibernateUtil.java文件,负责生成唯一一个SessionFactory
//SessionFaction单态模式
public class HibernateUtil {
private static SessionFactory sf=null;
private static Configuration cfg=null;
static {//在类加载的时候只能加载一次
try {
cfg = new Configuration().configure();
sf=cfg.buildSessionFactory();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static SessionFactory getSessionFactory() {
return sf;
}
public static void closeSessionFactory(){
sf.close();
}
2.Hibernate3中推荐使用getCurrentSession()方法创建Session,保证线程安全。
//3.创建一个session
//session =sf.openSession();
session =sf.getCurrentSession(); //保证每个读写线程有唯一的session实例
使用getCurrentSessi