要取消hibernate.cfg.xml的使用,但其中的配置信息却一点也不能少。
大体分三步,将这个配置文件分解进项目中。
1. 把过去Dao层一改,过去Dao里面有HibernateTemplate,由于没有了hibernate.cfg.xml,所以这个hibernateTemplate无法生成,只能使这个DaoImpl类继承HibernateDaoSupport ,然后需要用到hibernateTemplate时,只需要getHibernateTemplate() 便可。
顺便把applicationContext.xml中的关于hibernateTemplate给删了,sessionFactory中的属性configLocation给删了。
2.可以用配置文件:写在applicationContext.xml里
<context:property-placeholder location="classpath:c3p0-db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverclass}"></property>
...还有jdbc.Url , jdbc.User, jdbc.Password
</bean>
其中配置文件就是c3p0-db.properties,里面键为jdbc.driverclass 值为com.mysql.jdbc.Driver
...
然后修改sessionFactory的配置
<bean id="sessionFactory" class="...">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
...//把原来hibernate.cfg.xml中除了映射文件,全部属性加在这儿。
//注意很多属性值名称有变化,如hibernate.show_sql hibernate.format_sql 基本每个属性前都要加"hibernate."
</props>
</property>
</bean>
3.配置映射文件,同样给sessionFactory加一个属性
有几种方式:
1. mappingDirectoryLocations:设置目录,加载目录下全部hbm.xml
如设值为classpath:com/domian/
2.mappingJarLocations:加载jar包映射文件
3.mappingLocations:指定加载那些文件
如classpath:com/domain/User.hbm.xml , 它还支持 classpath:com/domain/*.hbm.xml
4.mappingResource: 加载src下的内容
比如com/domain/User.hbm.xml