前几天在配置hibernate的时候,遇到了一个问题,问题如下:
org.hibernate.HibernateException: G:/project_name/WEB-INF/hibernate.cfg.xml not
found
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configura
tion.java:1087)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1111)
at com.xilinhot.puma.HibernateSessionFactory.initSessionFactory(Hibernat
eSessionFactory.java:58)
at com.xilinhot.puma.HibernateSessionFactory.setConfigFileLocation(Hiber
nateSessionFactory.java:94)
该文件确确实实是存在的,为何找不到呢?习惯性的先Google了一下,反应该问题的人确实不少,但是,没有实质性的解决问题,什么更改hibernate.cfg.xml的字符编码了等等,简直是一派胡言,org.hibernate.HibernateException: G:/project_name/WEB-INF/hibernate.cfg.xml not found 实际就是 java.io.FileNotFoundException 另一种描述而已。
看来,还是要看看hibernate的源代码,找到org.hibernate.util.ConfigHelper文件,不看还好,看了真是感觉好笑,获取hibernate.cfg.xml文件,是默认在java Package里查找的:
public static InputStream getResourceAsStream(String resource) {
String stripped = resource.startsWith("/") ?
resource.substring(1) : resource;InputStream stream = null;
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader!=null) {
stream = classLoader.getResourceAsStream( stripped );
}
if ( stream == null ) {
stream = Environment.class.getResourceAsStream( resource );
}
if ( stream == null ) {
stream = Environment.class.getClassLoader().getResourceAsStream( stripped );
}
if ( stream == null ) {
throw new HibernateException( resource + " not found" );
}
return stream;
}呵呵,用的都是java.lang.Class或者java.lang.ClassLoader来获取InputStream对象的,在classpath路径外部的怎么可能找到呢?!得了,还是改改,重新编译一下吧,不然,想更改hibernate.cfg.xml文件里的数据时,还要重新编译class文件、打包jar文件,没必要。更新如下:
public static InputStream getResourceAsStream(String resource) {
String stripped = resource.startsWith("/") ?
resource.substring(1) : resource;InputStream stream = null;
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader!=null) {
stream = classLoader.getResourceAsStream( stripped );
}
if ( stream == null ) {
stream = Environment.class.getResourceAsStream( resource );
}
if ( stream == null ) {
stream = Environment.class.getClassLoader().getResourceAsStream( stripped );
}
//zhiyan modify at 2007.09.17 10:35
//add this step,can put the hibernate.cfg.xml anywhere
if ( stream == null ) {
try {
stream = new java.io.FileInputStream( resource );
} catch (java.io.FileNotFoundException fnfe) {
stream = null;
}
}
if ( stream == null ) {
throw new HibernateException( resource + " not found" );
}
return stream;
}将hibernate源文件编译、打包jar,将hibernate3.jar重新覆盖原来的文件。
重新进行测试,一切OK。
从整个事件来看,都是默认习惯惹得祸。每次都是默认放在project/src下的,编译、打包成jar后,hibernate.cfg.xml会放在project-1.1.jar里。
这样好了,自己的hibernate.cfg.xml可以随处放了。