您的位置:首页 > 编程语言 > Java开发

第五章 Spring3.0 、Hibernate3.3与Struts2的整合

2013-08-29 16:15 435 查看

5.1整合Spring与Hibernate

5.1.1使用MyEclipse加入Spring与Hibernate功能

使用MyEclipse工具主要是为了让工程拥有把数据表生成实体类与映射的功能。然后在这个过程中,把实体类或映射文件的路径加入到spring的配置文件中。而且在Spring与Hibernate整合后,我们不需要Hibernate的配置文件,Hibernate相关功能的配置都写在spring的配置文件中。


A、加入Spring功能

这个很简单,要注意的是,在加入Spring功能的步骤中,是否需要MyEclipse给我们提供的配置文件。如果是新的工程,一般都是需要的。





B、加入Hibernate功能

在加入Hibernate功能之前,我们必须得有Spring的配置文件,或者说我们必须在有Spring功能之后。

设置Hibernate的相关功能在Spring的配置文件中设置。如果还没有Spring的功能(配置文件),就选择New Spring configuration file,否则就按下面的下面的设置。SessionFactory Id是把SessionFactory类交由Spring管理时,它的Bean Id。





选择和配置数据源,这和Hibernate单独设置的时候是一样的。可参考Hibernate的文档(如下链接)。

http://blog.csdn.net/p_3er/article/details/8965305





C、移除MyEclipse给我们提供的Jar包,并导入我们的Jar包



把MyEclipse的Jar包移除后,把我们的Jar包放到项目的lib目录下,然后刷新工程。

5.1.2 配置数据源与SessionFactory

这个在上面5.1.1的过程中,已由MyEclipse自动帮我们配置好了。而映射文件或实体类的路径那是在通过MyEclipse中的工具把数据表生成实体类及映射的时候自动生成的。

<!-- 配置数据源 这个与JDBC整合的时候是一样的-->
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="test"/>
<property name="initialSize" value="5"/>
<property name="maxIdle" value="20"/>
<property name="minIdle" value="5"/>
<property name="maxActive" value="500"/>
</bean>

<!-- 配置SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 引入数据源 -->
<property name="dataSource">
<ref bean="dataSource" />
</property>

<!-- Hibernate的相关配置 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
</props>
</property>

<!-- 映射文件的路径。这是通过MyEclipse中的工具把数据表生成实体类及映射的时候自动生成的。 -->
<property name="mappingResources">
<list>
<value>cn/framelife/ssh/entity/User.hbm.xml</value>
</list>
</property>
</bean>


5.1.3 配置事务

除了事务管理类与JDBC时不一样之外,其它都相同。

http://blog.csdn.net/p_3er/article/details/9333521

<!-- 配置事务 -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="add*" rollback-for="Exception"/>
</tx:attributes>
</tx:advice>

<aop:config>
<aop:pointcut id="pointcut"
expression="execution(* cn.framelife.ssh.service..*(..))" />
<aop:advisor pointcut-ref="pointcut" advice-ref="txAdvice" />
</aop:config>


5.1.4 HibernateDaoSupport类的使用

当我们配置好SessionFactory后,就可以直接使用SessionFactory来生产Session,再用Session与数据库交互就行了。

Spring提供了org.springframework.orm.hibernate3.support.HibernateDaoSupport工具类,使Spring与Hibernate整合后,不再需要使用Hibernate的API,而使用HibernateDaoSupport类就可以拥有Hibernate API的功能。

数据层,*DaoImpl类实现*Dao接口,并继承HibernateDaoSupport类:

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
/**
* 保存或更新对象
*/
public void saveOrUpdateUser(User user) {
getHibernateTemplate().saveOrUpdate(user);
}

/**
* 根据id删除一条记录
*/
public void deleteById(Integer id) {
getHibernateTemplate().delete(this.findUserById(id));
}

/**
* 根据id获取一个记录对象
*/
public User findUserById(Integer id) {
return (User) getHibernateTemplate().get(User.class, id);
}

/**
* 根据Hql语句,以及开始位置、最大多少条数进行分页查询
*/
public List<User> findUserByLimit(final String hql, final int start,
final int limit) {
List<User> list = getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException,
SQLException {
Query query = session.createQuery(hql);
query.setFirstResult(start);
query.setMaxResults(limit);
List list = query.list();
return list;
}
});
return list;
}

/**
* 根据一个User对象查询与这个对象中的非空属性一致的数据
*/
public List<User> findUserByExample(User user) {
return getHibernateTemplate().findByExample(user);
}

/**
* 根据Hql语句查询多条记录对象
*/
public List<User> findUserByHql(String hql) {
return getHibernateTemplate().find(hql);
}
}


5.2集成Struts2

5.2.1 web.xml的配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- OpenSessionInViewFilter的主要功能是用来把一个Hibernate Session和一次完整的请求过程对应的线程相绑定 -->
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>

<!-- struts2的设置 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
<init-param>
<param-name>actionPackages</param-name>
<param-value>cn.framelife.ssh.struts</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>

<!-- 配置contextConfigLocation参数设置Spring配置文件的路径  -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

<!-- 通过配置ContextLoaderListener监听器,使服务器启动时,自动加载applicationContext配置,启动Spring容器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


5.2.2把*DaoImpl、*ServiceImpl及*Action等类交由Spring管理

<bean id="userDao" class="cn.framelife.ssh.dao.impl.UserDaoImpl">
<!-- 这里的sessionFactory属性是供HibernateDaoSupport使用的 -->
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="userService" class="cn.framelife.ssh.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="userAction" class="cn.framelife.ssh.struts.UserAction"  scope="prototype">
<property name="userService" ref="userService"></property>
</bean>


5.2.3配置struts2的Action

<struts>
<package name="a" extends="struts-default">
<!-- 整合spring后,这里的class是spring配置文件中的Action的Bean id -->
<action name="add" class="userAction">
<result name="success">/success.jsp</result>
</action>
</package>
</struts>


5.3 完整的Spring配置文件

<?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:p="http://www.springframework.org/schema/p"
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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- 数据源 -->
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="test"></property>
</bean>

<!-- 配置SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 引入数据源 -->
<property name="dataSource">
<ref bean="dataSource" />
</property>

<!-- Hibernate的相关配置 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
</props>
</property>

<!-- 映射文件或者映射类的路径。这是通过MyEclipse中的工具把数据表生成实体类及映射的时候自动生成的。 -->
<property name="mappingResources">
<list>
<value>cn/framelife/ssh/entity/User.hbm.xml</value>
</list>
</property>
</bean>

<!-- 配置事务 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="get*" read-only="true"/> <tx:method name="add*" rollback-for="Exception"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="pointcut" expression="execution(* cn.framelife.ssh.service..*(..))" /> <aop:advisor pointcut-ref="pointcut" advice-ref="txAdvice" /> </aop:config>
<!-- 管理Bean -->
<bean id="userDao" class="cn.framelife.ssh.dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="userService" class="cn.framelife.ssh.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="userAction" class="cn.framelife.ssh.struts.UserAction">
<property name="userService" ref="userService"></property>
</bean>
</beans>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息