[英]spring - hibernate load *.hbm.xml from classpath resource
我在classpath資源中有一些hbm.xml文件位於src / main / resources maven的文件夾中。 我使用spring的LocalSessionFactoryBean使用以下bean配置加載這些文件:
<bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSourceOracle"/>
<property name="mappingResources">
<list>
<value>mapping/SystemUser.hbm.xml</value>
<value>mapping/SystemCredential.hbm.xml</value>
<value>mapping/SystemProvince.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
</value>
</property>
</bean>
但它給了我FileNotFoundException。 請告訴我我做錯了什么,謝謝。
當使用帶有war
類型的項目的Maven時,位於src/main/resources
最終會出現在WEB-INF/classes
(並保留resources
目錄結構)。 因此,要么將映射文件放在src/main/resources/mapping
要么使用以下配置:
<bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSourceOracle"/>
<property name="mappingResources">
<list>
<value>SystemUser.hbm.xml</value>
<value>SystemCredential.hbm.xml</value>
<value>SystemProvince.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
</value>
</property>
</bean>
這看起來對我很好。 因此我不認為問題是配置。 我寧願認為文件根本不在類路徑上。 你是如何開始申請的?
如果您正在使用eclipse,請確保將src / main / resources用作源文件夾,並將資源復制到目標/類。
@Autowired
private ResourceLoader rl;
@Bean
public LocalSessionFactoryBean sessionFactory() throws IOException {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setMappingLocations(loadResources());
}
public Resource[] loadResources() {
Resource[] resources = null;
try {
resources = ResourcePatternUtils.getResourcePatternResolver(rl)
.getResources("classpath:/hibernate/*.hbm.xml");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resources;
}
在Web應用程序中,當您編寫沒有前綴的資源路徑時,Spring會從上下文根(即,從包含WEB-INF的文件夾)加載它。 要從類路徑加載資源,您應該使用“classpath:”前綴:
<value>classpath:mapping/SystemUser.hbm.xml</value>
如果從Web應用程序加載Spring應用程序上下文,您可能會看到如下錯誤:
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.io.FileNotFoundException: ServletContext resource [/hibernate.cfg.xml] cannot be resolved to URL because it does not exist
解決方案是明確告訴Spring從類路徑加載配置,如下所示:
classpath:mypath/myfile.xml
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.