一,配置文件加载
1,Configuration
如果不是annoation则可以使用Configuration configuration = new Configuration();
使用annoation则可以使用Configuration configuration = new AnnotationConfiguration();
2,加载,使用onfiguration的configure方法根据方法参数可以有一下几种加载方式:
(1) configure();
吃方法会去classpath下寻找我们的配置文件
其实调用了configure( "/hibernate.cfg.xml" );也就是 configure(String resource);方法
(2) configure(String resource);
最常用方的方法,其实调用了doConfigure(InputStream stream, String resourceName);
说明一点内部代码:
ConfigHelper.getResourceAsStream( 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;
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;
第一行高数我们"/hibernate.cfg.xml" 可以去掉前面的“/”其中调用了Thread.currentThread().getContextClassLoader();一般也就是我们的AppClassLoader
由stream = Environment.class.getResourceAsStream( resource );可以看出我们的"/hibernate.cfg.xml同样可以放在与和Environment同样的目录 具体到我们的代码里面在使用(3),(4),(5)时可以放在加载 类的包内或其他
(3) configure(URL url);
doConfigure( url.openStream(), url.toString() );调用(5)
(4) configure(File configFile);
doConfigure( new FileInputStream( configFile ), configFile.toString() );调用(5)
(5) doConfigure(InputStream stream, String resourceName);
使用dom4j解析文件为Document然后
xmlHelper.createSAXReader( resourceName, errors, entityResolver )
.read( new InputSource( stream ) );
掉用(6)
(6) configure(Document document);
在这个方法里会解析所有配置信息和mapping类或者hb文件