hibernate+spring动态加载hibernate映射文件
在维护公司的项目的时候遇到一个需求,表结构需要改动,实体类也需要改动,但该项目已经做成产品了,该修改还不能影响已经上线使用的其他版本,也不可以修 改其他版本的数据库,经过仔细考虑,决定采用动态加载hibernate映射文件的方式来实现。判断系统的版本配置,若为该版本,则加载a映射文件,将所 需属性映射到数据库,否则加载b映射文件,加的属性只以附加属性的方式存在。 首先,将需要动态加载的hibernate映射文件从hibernate映射文件或者spring的 org.springframework.orm.hibernate3.LocalSessionFactoryBean bean配置中去掉,重写一个类,
public class SaasSessionFactoryBean extends LocalSessionFactoryBean {
protected final Log log = LogFactory.getLog(getClass());
protected SessionFactory newSessionFactory(Configuration config) throws HibernateException
{
List<String> list = new ArrayList<String> ();
if(ResourceUtil.getChinahrtCurrentVersion().equals(VersionConstant.SAAS))
{
list.add("HrtLogOnlineForSaas.hbm.xml");
list.add("HrtCoursesTopForSaas.hbm.xml");
}else{
list.add("HrtLogOnline.hbm.xml");
list.add("HrtCoursesTop.hbm.xml");
}
try{
for(int i=0;i<list.size();i++){
URL url = HrtLogOnline.class.getResource(list.get(i));
File xmlFile = new File(url.toURI());
config.addFile(xmlFile);
System.out.println("动态添加映射文件"+xmlFile.toString());
}
}catch(Exception e)
{
e.printStackTrace();
}
log.info("构建sessionFactory...");
return config.buildSessionFactory();
}
spring中做如下配置:
SessionFactory bean
<bean id="chartSessionFactory" class="com.elemice.chart.olap.SaasSessionFactoryBean">
<property name="dataSource" ref="chartDataSource" />
<property name="mappingLocations">
<list>
<!-- <value>classpath*:com/landray/kmss/hrt/chart/model/*.hbm.xml</value> -->
<value>classpath:com/landray/kmss/hrt/chart/model/HrtPersonTrain.hbm.xml</value>
<value>classpath:com/landray/kmss/hrt/chart/model/HrtPersonCourse.hbm.xml</value>
<value>classpath:com/landray/kmss/hrt/chart/model/HrtPersonDetail.hbm.xml</value>
<value>classpath:com/landray/kmss/hrt/chart/model/HrtOrgsPersons.hbm.xml</value>
<value>classpath:com/landray/kmss/hrt/chart/model/HrtPersonsMsg.hbm.xml</value>
<value>classpath:com/landray/kmss/hrt/chart/model/HrtCourseTrain.hbm.xml</value>
<value>classpath:com/landray/kmss/hrt/chart/model/HrtChartLog.hbm.xml</value>
<value>classpath:com/landray/kmss/hrt/chart/model/HrtTrainMainC.hbm.xml</value>
<value>classpath:com/landray/kmss/hrt/chart/model/SysOrgElementC.hbm.xml</value>
<value>classpath:com/landray/kmss/hrt/chart/model/HrtCustomVido.hbm.xml</value>欠款
</list>
</property>
<property name="hibernateProperties">
<props>软件开发
<prop key="hibernate.dialect">${chartDB.hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${chartDB.hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${chartDB.hibernate.format_sql}</prop>
<prop key="hibernate.jdbc.fetch_size">${chartDB.hibernate.jdbc.fetch_size}</prop>
<prop key="hibernate.jdbc.batch_size">${chartDB.hibernate.jdbc.batch_size}</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop>
</props>
</property>
<property name="lobHandler" ref="defaultLobHandler2"></property>
</bean>
启动tomcat服务器,可以看到hibernate映射文件已经动态加载了。