[Java web]Spring+Struts2+Hibernate整合过程(2)
摘要
上篇文章介绍了一种整合方式,不妨就叫做有hibernate配置文件的方式,这里介绍一种不用hibernate.cfg.xml的一种配置方式,为了方便,就仍在上篇的demo中,继续修改了。
步骤
因为hibernate.cfg.xml中配置的是数据库的相关配置,以及映射关系,关于这部分配置完全可以在applicationContext.xml中进行整合。数据库的4要素也可以单独提取到jdbc.properties文件中。
在src目录下新建jdbc.properties文件,将4要素配置上
jdbc.driverClass=com.mysql.jdbc.Driver jdbc.jdbcUrl=jdbc:mysql:///sshdemo jdbc.user=root jdbc.password=abcd
在applicationContext.xml引入该文件即可
修改后配置如下
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="c3p0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driverClass}"/> <property name="user" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/> bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="c3p0DataSource"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialectprop> <prop key="hibernate.show_sql">trueprop> <prop key="hibernate.hbm2ddl.auto">updateprop> <prop key="hibernate.format_sql">trueprop> props> property> <property name="mappingResources"> <list> <value>com/ssh/domain/User.hbm.xmlvalue> list> property> bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> bean> <tx:annotation-driven transaction-manager="transactionManager"/> <bean class="com.ssh.dao.UserDao" id="userDao"> <property name="sessionFactory" ref="sessionFactory">property> bean> <bean id="userService" class="com.ssh.service.UserService"> <property name="userDao" ref="userDao">property> bean> <bean class="com.ssh.action.UserAction" id="userAction" scope="prototype"/> beans>
这时完全可以把hibernate.cfg.xml删除
测试结果