spring整合hibernate
一、加入sping
1、加入spring的jar,再加入spring集成hibernate的jar包
spring集成hibernate的jar包
2、配置web.xml,注意:application*.xml,可以在启动容器时实现多个配置文件的引入。
</pre><span style="white-space:pre"> </span><pre name="code" class="html"> <!-- needed for ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext*.xml</param-value>
</context-param>
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
3、src下加入applicationContext.xml
二、加入hibernate
1、加入jar
2、配置hibernate.cfg.xml文件
<session-factory>
<!-- 配置hibernate的基本属性-->
<!-- 配置方言 -->
<propertyname="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 配置 显示sql以及格式化-->
<propertyname="hibernate.show_sql">true</property>
<propertyname="hibernate.format_sql">true</property>
<!-- 数据表生成策略 -->
<propertyname="hibernate.hbm2ddl.auto">update</property>
</session-factory>
3、建立持久化类,以及相应的*.hbm.xml文件
注意:持久化类的关联关系。
3、和spring整合
①加入c3p0,mysql-connection.jar
<!--导入源文件db.properties -->
<context:property-placeholderlocation="classpath:db.properties"/>
<!-- 配置数据源-->
<beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource">
<propertyname="user" value="${jdbc.user}"></property>
<propertyname="password"value="${jdbc.password}"></property>
<propertyname="driverClass"value="${jdbc.driverClass}"></property>
<propertyname="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<propertyname="initialPoolSize"value="${jdbc.initPoolSize}"></property>
<propertyname="maxPoolSize"value="${jdbc.maxPoolSize}"></property>
</bean>
<!--配置sessionFactory
三个元素 | dataSource,hibernate.cfg.xml,*hbm.xml |
-->
<bean id="sessionFactory" class=
"org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<propertyname="dataSource" ref="dataSource"></property>
<propertyname="configLocation"value="classpath:hibernate.cfg.xml"></property>
<propertyname="mappingLocations"value="classpath:cn/edu/scnu/pojo/*.hbm.xml"></property>
</bean>
<!-- 配置声明式事务 -->
<bean id="transactionManager" class=
"org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置事务切面(aop) -->
<aop:config>
<aop:advisor advice-ref="" pointcut-ref=""/>
</aop:config>
声明式事务的最终配置:
配置到sessionFactory时启动项目,就会生成相对应的数据表。
四、spring整合struts2
1、加入jar包,如果有重复的需要删掉多余的jar包
2、配置web.xml,配置struts2的Filter
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3、加入struts.xml文件
4、整合spring
①加入struts2的spring插件的jar包
②在Spring的配置文件中正常配置Action,注意:Action的scope为propotype
③在struts2的配置文件中配置action时,class属性指向该action在IOC容器中的id