spring与hibernate集成--关于配置文件

spring对hibernate整合的相当完美,并且spring对hibernate配置文件hibernate.cfg.xml也做了整合,在spring中利用LocalSessionFactoryBean就可以把hibernate.cfg.xml文件的内容整合到spring的配置文件中,这确实相当好,减少了配置文件。其实,LocalSessionFactoryBean最吸引我的原因是mappingLocations属性,这是一个用来配置hibernate映射文件的属性,这个属性的好处是我可以使用通配符,简单一行就可以配置整个项目的映射文件,比如:

< property name ="mappingLocations" >
< list >
< value >
classpath:/com/company/callcenter/domain/**/maps/*.hbm.xml
</ value >
</ list >
</ property >


但是,加入由于某种原因,我需要使用独立hibernate.cfg.xml文件,但是又想保留spring的简单配置映射文件的方法,怎么办呢?
我想要单独列出hibernate.cfg.xml文件的原因是:
1.我使用jboss提供hiberante插件,那就需要一个独立hibernate.cfg.xml文件,因为这个插件的功能比较适用:HQL Editor、Criteria Editor、Code Genration等
2.插件的编辑器对hibernate.cfg.xml提供hibernate属性提示功能,很好用。在spring中,spring的DTD文件列出hibernate属性,这是因为hibernate属性名称可能会变化,而spring团队无法控制hibernate团队对hibernate配置属性名称的变化

基于以上需要,最后我结合了两种配置文件的优点,很好的解决了这个问题
关键点:
1.使用LocalSessionFactoryBean的mappingLocations配置映射文件
2.使用configLocation属性配置hibernate.cfg.xml文件
3.在hibernate.cfg.xml文件中配置除了数据库链接的属性,以及其他可以有spring代替的属性,比如事务
下面是两个文件的部分示例代码
applicationContext.xml

< bean id ="sessionFactory"
class
="org.springframework.orm.hibernate3.LocalSessionFactoryBean" >
< property name ="mappingLocations" >
< list >
< value >
classpath:/com/company/project/domain/**/maps/*.hbm.xml
</ value >
</ list >
</ property >
< property name ="configLocation" >
< value > /WEB-INF/spring-config/hibernate.cfg.xml </ value >
</ property >
< property name ="dataSource" >
< ref local ="dataSource" />
</ property >
</ bean >

hibernate.cfg.xml

< hibernate-configuration >
< session-factory name ="CallCenter" >
< property name ="hibernate.dialect" >
org.hibernate.dialect.Oracle9Dialect
</ property >
< property name ="hibernate.connection.driver_class" >
oracle.jdbc.driver.OracleDriver
</ property >
< property name ="hibernate.connection.url" >
jdbc:oracle:oci:@test
</ property >
< property name ="hibernate.connection.username" >
test
</ property >
< property name ="hibernate.connection.password" > test </ property >

< property name ="hibernate.cache.provider_class" >
org.hibernate.cache.EhCacheProvider
</ property >
< property name ="hibernate.show_sql" > true </ property >
< property name ="hibernate.max_fetch_depth" > 3 </ property >
< property name ="hibernate.bytecode.use_reflection_optimizer" >
true
</ property >
< property name ="hibernate.query.substitutions" >
true1,false0,yes'Y',no'N'
</ property >
</ session-factory >
</ hibernate-configuration >

上述配置也有一点小小的缺憾,那就两个地方配置了数据源,系统真正用到的spring配置的数据源,hibernate.cfg.xml中的数据源是留给hibernate插件使用的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值