SHH整合进阶(注解版)

SHH整和

三大框架架构(整合原理)

spring与struts2整合就是将action对象交给spring容器来负责创建
spring与hibernate整合就是将sessionFactory交给spring来维护(维护session和aop事务)

具体操作

1、 导包

Hibernate
1、hibernate中的require文件夹下的所有jar包共10个。
2、在一些hibernate版本中还需要导入java的持久化规范包hibernate-entrymanager-xxx.jar包。
3、数据库驱动包。
Struts2

1、Struts.blank文件夹下的必须包(也可以根据自己需求挑选)
    注意::javassist-3.18.1-GA.jar包与hibernate中的重复,建议删除版本低的。
2、struts整合spring插件包:Struts-spring-plugin-xxx.jar。
    注意:导入此包后,struts2会在启动时寻找spring容器,找不到将会抛出异常。
Spring

1、基本jar包(4+2)
    core+beans+context+expression
    logging+log4j
2、整合web包
    spring-web
3、整合aop包
    spring-aop+spring-aspect+(第三方)aopalliance+(第三方)aopweaving
4、整合Hibernate和事务包
    spring-jdbc+spring-tx+c3p0+spring-orm
5、整合JUnit4测试包
    spring-test

标签库

1、jstl标签库
    jstl+standard

2、 配置spring容器

1、在web.xml中的配置
<!-- 配置spring容器随web项目创建而启动 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 配置spring配置文件的位置 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
2、配置src目录下的applicationContext.xml
    spring配置文件中中需要导入的约束: beans/aop/context/tx
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.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 "
    default-autowire="byName">

    <!-- 开启使用注解代理配置文件 -->
    <context:component-scan base-package="com.hytXwz"></context:component-scan>

</beans>

注意:spring+struts2+hibernate 框架整合时,持久层继承了HibernateDaoSupper时,用注解方法可能会在持久层报sessionFactory或HibernateTemple为必须的,表明没有注入sessionFactory。
主要原因是spring的头声明需要在最后添加default-autowrite=“byName”
spring容器搭建成功。

3、 将struts2整合进spring容器

1、在web.xml中配置struts2核心过滤器
<!-- 配置struts2核心过滤器到wen.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>
2、配置struts2主配置文件
<!-- 配置由spring来创建action对象 -->
        <constant name="struts.objectFactory" value="spring"></constant>
        <!-- 配置spring来装配action的依赖属性(默认) -->
        <constant name="struts.objectFactory.spring.autoWire" value="name"></constant>

        <package name="userAction" namespace="/" extends="struts-default">
            <!-- 将UserActon配置到spring容器,直接用beanname取出UserAction -->
            <!-- UserAction_*可以通配多个useraction -->
            <action name="UserAction_*" class="userAction" method="{1}">
                <result name="success" type="dispatcher">/default.jsp</result>
            </action>
        </package>

4、测试整合了struts2的spring

1、UserAction
@Controller("userAction")
@Scope(scopeName="prototype")
public class UserAction extends ActionSupport{
    //继承ActionSupport帮我们实现了一些接口,无需自己实现

    private static final long serialVersionUID = 3339585342231210528L;

    @Resource(name="userService")
    private UserService us;

    @Override
    public String execute() throws Exception {
        return super.execute();
    }


}
2、UserService
@Service("userService")
public class UserServiceImpl implements UserService{

    @Override
    public User getByCodePassword() {
        System.out.println("UserServiceImpl");
        return null;
    }

}
将项目发布到tomcat访问UserAction自动跳转到default.jsp并在控制台打印内容即配置成功

5、spring整合c3p0连接池

1、配置db.properties(在键前面添加jdbc.避免出现重复导致读取信息错误)
jdbc.jdbcUrl=jdbc:mysql:///spring
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=wangyinpeng
    2、在applicationContext.xml中读取properties文件中的内容创建c3p0连接池
<!-- 配置读取db.properties文件中的内容 -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 通过读取db.properties中的内容创建c3p0连接池 -->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

6、spring整合hibernate

<!-- spring整合hibernate
            原理:将sessionFactory交给spring来维护
            spring-orm下的hibernate5中的LocalSessionFactoryBean对象
     -->
     <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 将连接池注入给sessionFactory,hibernate会通过连接池获得连接 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- hibernate基本配置 -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql" >true</prop>
                <prop key="hibernate.format_sql" >true</prop>
                <prop key="hibernate.hbm2ddl.auto" >update</prop>
            </props>
        </property>
        <!-- 引入orm元数据,指定orm元数据所在的包路径,spring会自动读取包中的所有配置
            注意路径要用/
          -->
        <property name="mappingDirectoryLocations" value="classpath:com/hytXwz/domain"></property>
     </bean>
Dao类创建:继承hibernateDaoSupport
通过super.getHibernateDaoSupport()来获得hibernate模板对象来操作数据库
hibernate模板对象操作数据库还是通过session来操作所以Dao类依赖sessionFactory

7、spring的aop事务

<!-- 配置aop核心事务管理器hibernate(封装了事务操作) -->
    <bean name="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <!-- hibernate管理事务是通过sessionFactory所以依赖sessionFactory -->
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- 开启注解事务 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

Service层

@Service("userService")
@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)
public class UserServiceImpl implements UserService{

    @Resource(name="userDao")
    private UserDao ud;

    @Override
    @Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=true)
    public User getByCodePassword(User u) {
        return ud.getByCodePassword(u);
    }

}

8、扩大session作用范围

<!-- 扩大session的作用范围
    注意:任何filter要配置在struts2核心过滤器之前,因为struts的过滤器中没有放行代码
   -->
  <filter>
    <filter-name>openSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>openSessionInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
    ##通过注解搭建SHH整合框架完成啦!##

                        技术交流群:713788313  期待你的加入

猜你喜欢

转载自blog.csdn.net/hytxwz/article/details/80457232