package com;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import javax.naming.InitialContext;
/**
* 说明:hibernate初始化类,如果是运行期,将从上下文中取得sessionFactory
*
* 2004-8-4
*/
public class HibernateInit {
private static HibernateInit instance= null;
private static SessionFactory sessionFactory;
//运行类型是服务器运行还是单元测试,如果是单元测试,设置其参数值为junit
private static String runType= "web";
public static void setRunType(String type) {
runType= type;
}
public synchronized static HibernateInit getInstance() {
if (instance == null) {
instance= new HibernateInit();
}
return instance;
}
private HibernateInit() {
initSessionFactory();
}
private void initSessionFactory() {
Configuration conf;
try {
if (runType != null && runType.equalsIgnoreCase("junit")) {
java.net.URL configFileURL= GenerateDataBaseUtil.class.getResource("/hibernate_GenerateDB.cfg.xml");
conf= (new Configuration()).configure(configFileURL);
sessionFactory= conf.buildSessionFactory();
} else {
InitialContext ctx= new InitialContext();
sessionFactory= (SessionFactory) ctx.lookup("hibernate/session_factory");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
}
本文地址:http://com.8s8s.com/it/it10305.htm