因为tomcat不能自动加载hibernate.cfg.xml文件,所以就写了一个servlet,其关键代码如下:
public void init() throws ServletException{
context=this.getServletContext();
try {
SessionFactory myFactory=(SessionFactory)context.getAttribute("myFactory");
if(myFactory==null){
SessionFactory sessionFactory=MySessionFactory.getSessionFactory();
context.setAttribute("myFactory", sessionFactory); }
} catch (Exception e) {
e.printStackTrace();
} }
接着在web.xml中配置了该servlet,重启tomcat后,该servlet顺利执行,但是控制台却并没有初始化hibernate.cfg.xml的相应信息,即hibernate.cfg.xml并没有被真正的初始化,不知道是什么原因?
注:
1、该servelt是正常运行了的,并没有抛出任何异常。
2、MySessionFactory实际上是导入hibernate包时,自动创建的类文件,即session工厂,getSessionFactory()中有加载配置文件的实现代码,如下:
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
} return session;
}
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% 创建 SessionFactory时错误! %%%%");
e.printStackTrace();
}
}
public void init() throws ServletException{
context=this.getServletContext();
try {
SessionFactory myFactory=(SessionFactory)context.getAttribute("myFactory");
if(myFactory==null){
SessionFactory sessionFactory=MySessionFactory.getSessionFactory();
context.setAttribute("myFactory", sessionFactory); }
} catch (Exception e) {
e.printStackTrace();
} }
接着在web.xml中配置了该servlet,重启tomcat后,该servlet顺利执行,但是控制台却并没有初始化hibernate.cfg.xml的相应信息,即hibernate.cfg.xml并没有被真正的初始化,不知道是什么原因?
注:
1、该servelt是正常运行了的,并没有抛出任何异常。
2、MySessionFactory实际上是导入hibernate包时,自动创建的类文件,即session工厂,getSessionFactory()中有加载配置文件的实现代码,如下:
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
} return session;
}
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% 创建 SessionFactory时错误! %%%%");
e.printStackTrace();
}
}
虽然整个方法从头到尾运行了……
唉,苦闷啊