美文网首页我爱编程
Spring + SpringMVC + Hibernate整合

Spring + SpringMVC + Hibernate整合

作者: _Raye | 来源:发表于2017-03-30 10:01 被阅读0次

    整合需要的依赖包:(pom.xml)

          <!-- log4j 日志 -->  
            <dependency>  
                <groupId>log4j</groupId>  
                <artifactId>log4j</artifactId>  
                <version>1.2.17</version>  
            </dependency>  
            <!-- servlet API -->  
            <dependency>  
                <groupId>javax.servlet</groupId>  
                <artifactId>javax.servlet-api</artifactId>  
                <version>3.1.0</version>  
                <scope>provided</scope>  
            </dependency>  
          <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
            <scope>provided</scope>
        </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
            <!-- MySQL驱动 -->  
            <dependency>  
                <groupId>mysql</groupId>  
                <artifactId>mysql-connector-java</artifactId>  
                <version>5.1.40</version>  
            </dependency>  
            <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.1.1</version>
        </dependency>
            <!-- junit -->  
            <dependency>  
                <groupId>junit</groupId>  
                <artifactId>junit</artifactId>  
                <version>4.12</version>  
                <scope>test</scope>  
            </dependency>  
            <!-- fastjson -->  
            <dependency>  
                <groupId>com.alibaba</groupId>  
                <artifactId>fastjson</artifactId>  
                <version>1.1.29</version>  
            </dependency>
          <!-- spring -->  
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-core</artifactId>  
                <version>4.3.7.RELEASE</version>  
            </dependency>  
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-context</artifactId>  
                <version>4.3.7.RELEASE</version>  
            </dependency>  
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-jdbc</artifactId>  
                <version>4.3.7.RELEASE</version>  
            </dependency>  
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-beans</artifactId>  
                <version>4.3.7.RELEASE</version>  
            </dependency>  
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-web</artifactId>  
                <version>4.3.7.RELEASE</version>  
            </dependency>  
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-webmvc</artifactId>  
                <version>4.3.7.RELEASE</version>  
            </dependency>  
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-expression</artifactId>  
                <version>4.3.7.RELEASE</version>  
            </dependency>  
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-orm</artifactId>  
                <version>4.3.7.RELEASE</version>  
            </dependency>  
          <!-- aspectjrt -->  
            <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.10</version>
        </dependency>
            <!-- aspectjweaver -->  
            <dependency>  
                <groupId>org.aspectj</groupId>  
                <artifactId>aspectjweaver</artifactId>  
                <version>1.8.10</version>  
            </dependency>  
            <!-- hibernate -->  
            <dependency>  
                <groupId>org.hibernate</groupId>  
                <artifactId>hibernate-core</artifactId>  
                <version>5.2.8.Final</version>  
            </dependency>
    <!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.10.19</version>
        </dependency>
    

    web.xml 与 (前端控制器名-servlet.xml) 都在WEB-INF下

    • 如果用到struts,需在web.xml中配置struts过滤器(web.xml):
      本次讲的是SpringMVC,所以与struts无关,可跳过struts配置
    <!-- struts前端控制器(由它来决定走那个Action,它会读取struts.xml文件来决定) -->
        <filter>
            <filter-name>struts2</filter-name>
            <filter-class>
                org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
            </filter-class>
        </filter>
     
        <!-- 所有的请求都要经过这个过滤器 -->
        <filter-mapping>
            <filter-name>struts2</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
    • 如果用到SpringMVC,需在web.xml中配置SpringMVC的前端控制器(web.xml):
    <!-- springMVC前端控制器 -->
        <servlet>
            <servlet-name>frontController</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>frontController</servlet-name>
    <!-- 配/表示不会覆盖默认设置(server里面的web.xml) -->
    <!-- 配*.do表示只有.do的资源走这里,静态资源不受管理 -->
            <url-pattern>*.do</url-pattern> 
        </servlet-mapping>
    
    • 与SpringMVC对应的xml文件( 前端控制器名-servlet.xml )
      这里是frontController-servlet.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:mvc="http://www.springframework.org/schema/mvc"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.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">
            
            <!-- 配置搜索组件的基础包 (将被注解的类的对象纳入spring IoC容器的管理) -->
            <context:component-scan base-package="com.qfedu.dang.controller"/>
            <!-- 使用注解来配置需要spring IoC容器托管的对象以及对象之间的依赖关系 -->
            <context:annotation-config/>
            <!-- 配置Spring的Bean的验证器(可通过@Pattern(regexp = "\\w{4,20}")写正则表达式来验证,再在controller中对应的地方打上@Valid) -->
            <bean id="globalValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>            
            <!-- 配置json消息转换器 -->
            <mvc:annotation-driven validator="globalValidator">
                <mvc:message-converters>
                    <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
                    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
                    <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
                </mvc:message-converters>
            </mvc:annotation-driven>  
    
        <!-- 配置springMVC的视图解析器(渲染视图完成模型和视图的绑定) -->
        <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
            <property name="prefix" value="/WEB-INF/jsp/" />
            <property name="suffix" value=".jsp" />
        </bean>
            
        <!-- 配置处理文件上传的解析器 -->
        <bean id="multipartResolver"
            class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1048576"/>
        </bean> 
    </beans>
    
    • 配置spring配置文件的位置(app.xml的位置):(web.xml)
    <!-- 通过配置上下文参数指定Spring配置文件的位置 -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:app.xml</param-value>
        </context-param>
    
    • 配置IoC容器上下文监听器(web.xml)
    <!-- 配置创建IoC容器的上下文监听器 -->
        <listener>
            <listener-class>
                org.springframework.web.context.ContextLoaderListener
            </listener-class>
        </listener>
    
    • 配置编码过滤器:(web.xml)
    <!-- 设置处理编码的过滤器 -->
        <filter>
            <filter-name>enc</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>utf-8</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>enc</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    

    app.xml 在 src 根目录下

    • Hibernate中的注解
      @Entity实体类
      @Table表
      @Id主键
      @Column字段名
      @GeneratedValue(strategy = GenerationType.IDENTITY)主键生成策略
      @Transient隐藏字段
      @ManyToOne
      @OneToMany(mappedBy,cascade=CascadeType.ALL)双向关联
      @JoinColumn连接字段
      @Embeddable标注嵌入式主键类,表示这个是一个嵌入式类(实现Serializable接口)
      @Embedded 标注实体中的嵌入式主键

    • <context:component-scan base-package="com.qfedu.dang"/>
      Spring IoC容器会纳入@Component,@Service,@Controller,@Repository注解的类进行管理

    <?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:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.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
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
            
            <!-- 配置搜索组件的基础包 (将被注解的类的对象纳入spring IoC容器的管理) -->
            <context:component-scan base-package="com.qfedu.dang"/>
            <!-- 使用注解来配置需要spring IoC容器托管的对象以及对象之间的依赖关系 -->
            <context:annotation-config/>
            <!-- 配置为基于AspectJ的切面自动生成代理 -->
            <aop:aspectj-autoproxy/>
    
        <!-- 配置数据库连接池(空间换时间的优化) -->
        <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/dang?useUnicode=true&characterEncoding=utf8"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
            <property name="initialSize" value="10"/>
            <property name="maxTotal" value="50"/>
            <property name="maxWaitMillis" value="15000"/>
        </bean>
    
        <!-- 配置Hibernate的会话工厂(持久层需要依赖的对象) -->
        <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <!-- @Entity -->
            <property name="packagesToScan" value="com.qfedu.dang.entity"/>           
            <property name="hibernateProperties">
                <value>
                    hibernate.dialect=org.hibernate.dialect.MySQLDialect
                    hibernate.show_sql=true
                    hibernate.format_sql=true
                </value>
            </property>
        </bean>
    
        <!-- 配置spring为Hibernate提供的事务管理器 -->
        <bean id="transactionManager"
                class="org.springframework.orm.hibernate5.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory"/>
        </bean>
    
        <!-- 配置使用注解来声明事务 -->
        <tx:annotation-driven/>  
           
    </beans>
    
    • hibernate运行原理
    1.读取并解析配置文件 
    2.读取并解析映射信息,创建SessionFactory 
    3.打开Sesssion 
    4.创建事务Transation 
    5.持久化操作 
    6.提交事务 
    7.关闭Session 
    8.关闭SesstionFactory 
    
    • SpringMVC注解
      1.@RequestMapping("/reg") 表示访问reg.do
      方法最后返回的字符串是返回的jsp页面
      2.@RequestParam - 请求参数(表单或者查询字符串)
      3.@CookieValue - Cookie中拿参数
      4.@RequestHeader - 请求头拿参数
      5.@PathVariable - 路径参数("/student/123005")
      6.@ResponseBody 将内容或对象作为 HTTP 响应正文返回,并调用适合HttpMessageConverter的Adapter转换对象,写入输出流
      7.@RequestBody 将HTTP请求正文转换为适合的HttpMessageConverter对象

    相关文章

      网友评论

        本文标题:Spring + SpringMVC + Hibernate整合

        本文链接:https://www.haomeiwen.com/subject/ytsuottx.html