spring配置hibernate的sessionFactory
之前用spring2+hibernate3+struts2开发了一个彩信发布系统,由于第一次使用此架构,造成applicationContext.xml中的配置非常冗长,而且经常因为更改一个小配置项(例:数据库ip、用户名、密码等)将此文件作修改,这及不利于项目维护,万一粗心造成其他地方变动,会对本来正常的项目造成bug
其实那个项目我最后做了分隔,将applicationContext.xml分隔成好几段,但是我觉得其实对于数据库方面的配置,完全可以通过加载hibernate.cfg.xml配置文件来配置项目的sessionFactory,所以这个新项目我决定使用此方式
这里介绍一下spring加载sessionFactory的这2种方式
1、通过配置dataSource来配置sessionFactory
applicationContext.xml
destroy-method="close">
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
org.hibernate.dialect.MySQLDialect
true
使用 mappingDirectoryLocations 属性可以指定某目录下的 hbm 文件(“classpath*:”指向 WEB-INF/classes 目录)
classpath:com/tukechina/mms/pojos
补充:使用 mappingResources 属性要一个一个写 hbm 文件(“classpath*:”指向 WEB-INF/classes 目录)
classpath*:/test/domain/MyBean.hbm.xml
classpath*:/test/domain/BasicBean.hbm.xml
2、通过加载hibernate.cfg.xml来配置sessionFactory
applicationContext.xml
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
hibernate.cfg.xml
/p>
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
com.mysql.jdbc.Driver
1234
jdbc:mysql://localhost/goodshool
root
org.hibernate.dialect.MySQLDialect
true
20
5
120
100
120
2
true
对于第二种配置方案,找到的资料很少,大多数采用第一种,其实还有一种较好的配置
3、通过配置jdbc.properties文件分离数据库的配置
jdbc.properties
Mysqljdbc.driverClassName=com.mysql.jdbc.Driver
Mysqljdbc.url=jdbc:mysql://localhost/goodshool
Mysqljdbc.username=root
Mysqljdbc.password=1234
# second cache statistics
hibernate.generate_statistics=true
# Property that determines the Hibernate dialect
# (only applied with "applicationContext-hibernate.xml")
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
applicationContext.xml
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
destroy-method="close">
${Mysqljdbc.driverClassName}
${Mysqljdbc.url}
${Mysqljdbc.username}
${Mysqljdbc.password}
5
2
20
600
120
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
${hibernate.generate_statistics}
${hibernate.dialect}
${hibernate.show_sql}
classpath:com/shangx/pojos