一、单例模式
1.在第一个项目的基础上将创建sessionfactory的代码封装成一个类,在manager中再去调用它。在static代码块中操作只会执行一次
package cn.hrbust.dao;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
//SessionFactory单态模式
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.在hibernate.cfg.xml的 < session-factory>标签