0 从web.xml出发
项目中用Spring整合Hibernate,Spring贯穿整个项目,所以先看看Spring在哪一步整合了Hibernate。先看部分web.xml。
在context-param设定参数contextConfigLocation。
在listener配置基于Web上下文级别的监听器ContextLoaderListener,它会加载contextConfigLocation中的配置文件。
其中最重要的是spring-hibernate.xml,这里面配置了hibernate。
contextConfigLocation
classpath:spring.xml,classpath:spring-ehcache.xml,classpath:spring-hibernate.xml
org.springframework.web.context.ContextLoaderListener
1 spring-hibernate.xml
1.1 配置数据源
1.2 配置hibernate session工厂
${hibernate.hbm2ddl.auto}
${hibernate.dialect}
${hibernate.show_sql}
${hibernate.format_sql}
${hibernate.use_sql_comments}
light.mvc.model
1.3 配置事务管理(AOP)
2 spring-hibernate.xml
spring.xml中加载了一些数据库参数,参数在config.properties文件中进行设置,比如jdbc_url、jdbc_username、jdbc_password这些参数。
同时扫描service组件和dao组件实现自动注入。
classpath:config.properties
3 config.properties文件
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://222.222.222.222:3306/xxx?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&&autoReconnect=true
jdbc_username=xxx
jdbc_password=xxx
hibernate.hbm2ddl.auto=none
hibernate.show_sql=false
hibernate.format_sql=false
hibernate.use_sql_comments=false
4 如果想操作两个数据库
config.properties配置文件中,新增数据库url,username和password
spring-hibernate.xml中复制一个新的数据源,复制的数据源需要修改bean的name,以及属性url、username和password的值
spring-hibernate.xml中复制一个新的session工厂复制的session工厂需要修改bean的id,以及属性dataSource和packagesToScan
spring-hibernate.xml中复制一个新的事务管理器,修改bean的name和sessionFactory属性
结合本项目框架,在spring-hibernate中还需配置新的tx:advice和aop:config标签
在Dao操作中使用新配置的sessionFactory进行操作,即可对新数据库进行操作