一,配置文件加載
1,Configuration
如果不是annoation則可以使用Configuration configuration = new Configuration();
使用annoation則可以使用Configuration configuration = new AnnotationConfiguration();
2,加載,使用onfiguration的configure方法根據(jù)方法參數(shù)可以有一下幾種加載方式:
(1) configure();
吃方法會(huì)去classpath下尋找我們的配置文件
其實(shí)調(diào)用了configure( "/hibernate.cfg.xml" );也就是 configure(String resource);方法
(2) configure(String resource);
最常用方的方法,其實(shí)調(diào)用了doConfigure(InputStream stream, String resourceName);
說明一點(diǎn)內(nèi)部代碼:
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;
第一行高數(shù)我們"/hibernate.cfg.xml" 可以去掉前面的“/”其中調(diào)用了Thread.currentThread().getContextClassLoader();一般也就是我們的AppClassLoader
由stream = Environment.class.getResourceAsStream( resource );可以看出我們的"/hibernate.cfg.xml同樣可以放在與和Environment同樣的目錄 具體到我們的代碼里面在使用(3),(4),(5)時(shí)可以放在加載 類的包內(nèi)或其他
(3) configure(URL url);
doConfigure( url.openStream(), url.toString() );調(diào)用(5)
(4) configure(File configFile);
doConfigure( new FileInputStream( configFile ), configFile.toString() );調(diào)用(5)
(5) doConfigure(InputStream stream, String resourceName);
使用dom4j解析文件為Document然后
xmlHelper.createSAXReader( resourceName, errors, entityResolver )
.read( new InputSource( stream ) );
掉用(6)
(6) configure(Document document);
在這個(gè)方法里會(huì)解析所有配置信息和mapping類或者h(yuǎn)b文件