1. 程式人生 > >springmvc,spring,hibernate框架整合

springmvc,spring,hibernate框架整合

首先工作是匯入jar包

需要的jar包:
測試需要的jar包 junit

spring系列的jar包 spring-webmvc(spring-aop spring-beans spring-context spring-core spring-expression
spring-web)
spring-jdbc
spring-orm
aspectjweaver
aspectjrt
aopalliance aop切面

hibernate jar包 hibernate-core
hibernate-ehcache

連線資料庫的jar包 commons-logging
commons-dbcp(commons-pool)
mysql-connector-java

日誌的jar包 slf4j-api
slf4j-log4j12
log4j-core

檔案上傳 commons-fileupload

轉json fastjson

快取 ehcache

配置檔案

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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--開啟註解掃描功能-->
    <context:annotation-config></context:annotation-config>
    <!--定義註解掃描的包-->
    <context:component-scan base-package="com.qy.dao"></context:component-scan>
    <context:component-scan base-package="com.qy.service"></context:component-scan>
    <context:component-scan base-package="com.qy.domain"></context:component-scan>
    <!--開啟aop自動代理模式-->
    <aop:aspectj-autoproxy proxy-target-class="true"/>
    <!--從上下文環境中讀取db.properties配置檔案-->
    <context:property-placeholder location="classpath*:db.properties"></context:property-placeholder>
    <bean id="dataSource"  class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${dbcp.driverClassName}"></property>
        <property name="url" value="${dbcp.url}"></property>
        <property name="username" value="${dbcp.username}"></property>
        <property name="password" value="${dbcp.password}"></property>
        <property name="maxActive" value="${dbcp.maxActive}"></property>
        <property name="initialSize" value="${dbcp.initialSize}"></property>
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 配置Hibernate的SessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!--指定當前會話工廠使用的資料來源-->
        <property name="dataSource" ref="dataSource"></property>
        <!--指定實體類的位置-->
        <property name="packagesToScan"  value="com.qy.domain"/>
       <!-- <property name="annotatedClasses">
            <list>
                <value>com.qy.domain.Province</value>
            </list>
        </property>-->
        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.MySQLDialect
                hibernate.show_sql=true
                hibernate.format_sql=true
                <!--  hibernate.hbm2ddl.auto=create -->
            </value>
        </property>
    </bean>
    <!-- 配置 HibernateTemplate -->
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- 配置spring的宣告性事務 -->
    <bean  id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <!-- 要根據hibernate的版本配置 -->
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- 配置事務屬性 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*"    propagation="REQUIRED"/>
            <tx:method name="update*"  propagation="REQUIRED"/>
            <tx:method name="delete*"  propagation="REQUIRED"/>
            <tx:method name="*" propagation="NOT_SUPPORTED"></tx:method>
        </tx:attributes>
    </tx:advice>
    <!-- 配置事務切入點 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.qy.service.impl.*.*(..))" id="pointCut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"/>
    </aop:config>
</beans>

springmvc-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: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/context
		        http://www.springframework.org/schema/context/spring-context.xsd
		        http://www.springframework.org/schema/mvc
		        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--檢視解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--指定檢視的字首和字尾,Controller返回的String型別與這裡的前後綴拼接,構成返回的檢視頁面地址-->
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--開啟註解掃描功能-->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!-- 處理請求返回json字串的中文亂碼問題 -->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <!-- 解決Controller返回json中文亂碼問題 -->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <!-- <property name="supportedMediaTypes" value="text/html;charset=UTF-8" /> -->
                <!-- <property name="supportedMediaTypes" value="application/json;charset=UTF-8" > -->
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
            <!-- fastJson配置 -->
            <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/json;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <!--定義註解掃描的包-->
    <context:component-scan base-package="com.qy.controller"></context:component-scan>
    <!--處理靜態資源-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>
    <!--將連結中的靜態的訪問路徑對映為URL,常用於載入html、js、css、圖片、視訊等靜態資源-->
    <mvc:resources mapping="/js/**" location="/js/"/>
    <mvc:resources mapping="/images/**" location="/images/"/>
    <mvc:resources mapping="/css/**" location="/css/"/>
    <!--springmvc定義好的,用來處理上傳檔案的類-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 設定上傳檔案的最大尺寸為1MB -->
        <property name="maxUploadSize">
            <value>1048576</value>
        </property>
    </bean>
 </beans>

新增web目錄,配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <!-- Spring的OpenSessionInView實現 -->
    <filter>
        <filter-name>openSessionInViewFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter
        </filter-class>
        <!-- singleSession預設為true,若設為false則等於沒用OpenSessionInView 。所以預設可以不寫-->
        <init-param>
            <param-name>singleSession</param-name>
            <param-value>true</param-value>
        </init-param>
        <!--
        指定org.springframework.orm.hibernate3.LocalSessionFactoryBean在spring配置檔案中的名稱,預設值為sessionFactory。 如果LocalSessionFactoryBean在spring中的名稱不是sessionFactory,該引數一定要指定,否則會出現找不到sessionFactory的例外。所以預設可以不寫
        -->
        <init-param>
            <param-name>sessionFactoryBean</param-name>
            <param-value>sessionFactory</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>openSessionInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--filter 過濾器 用來解決中文亂碼問題-->
    <filter>
        <filter-name>characterEncoding</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>characterEncoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>default1</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>default1</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--配置spring-->
    <!-- 配置去哪裡載入spring的配置檔案 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!-- 配置spring的監聽器,載入資源初始化檔案 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

新增資料庫連線配置檔案

db.properties

dbcp.driverClassName=com.mysql.jdbc.Driver
dbcp.url=jdbc:mysql://localhost:3306/onetomore
dbcp.username=root
dbcp.password=123456
dbcp.maxActive=100
dbcp.initialSize=5

在applicationContext.xml中配置讀取db.properties的配置

使用${}讀取檔案,這裡我前面加個字首,不然讀取不了,一定跟前面的name=“”不一樣就行

<!--從上下文環境中讀取db.properties配置檔案-->
    <context:property-placeholder location="classpath*:db.properties"></context:property-placeholder>

    <bean id="dataSource"  class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${dbcp.driverClassName}"></property>
        <property name="url" value="${dbcp.url}"></property>
        <property name="username" value="${dbcp.username}"></property>
        <property name="password" value="${dbcp.password}"></property>
        <property name="maxActive" value="${dbcp.maxActive}"></property>
        <property name="initialSize" value="${dbcp.initialSize}"></property>
    </bean>

新增hibernate,生成實體類

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>

        <property name="connection.url">jdbc:mysql://localhost:3306/java1807</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>

        <!--資料庫表示什麼引擎,它就是什麼引擎-->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>


        <!--顯示sql-->
        <property name="hibernate.show_sql">true</property>
        <!--美化sql,格式化sql語句-->
        <property name="hibernate.format_sql">true</property>

        <!--使用二級快取-->
        <property name="hibernate.cache.use_second_level_cache">true</property>
        <!--配置二級快取服務商-->
        <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
        <!--使用查詢快取-->
        <property name="cache.use_query_cache">true</property>
        
        <mapping resource="Area.hbm.xml"/>
        <mapping resource="City.hbm.xml"/>
        <mapping resource="Province.hbm.xml"/>
        
      <!--  <mapping class="com.qy.domain.Province"></mapping>
        <mapping class="com.qy.domain.City"></mapping>
        <mapping class="com.qy.domain.Area"></mapping>-->
        <!-- <property name="connection.username"/> -->
        <!-- <property name="connection.password"/> -->

        <!--配置讀寫-->

        <class-cache class="com.qy.domain.Province" usage="read-write"></class-cache>
        <!-- DB schema will be updated if needed -->
        <!-- <property name="hbm2ddl.auto">update</property> -->
    </session-factory>
</hibernate-configuration>

將hibernate和spring整合

刪除hibernate.cgf.xml檔案,把hibernate的檔案配置在application.xml中

  <!-- 配置Hibernate的SessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!--指定當前會話工廠使用的資料來源-->
        <property name="dataSource" ref="dataSource"></property>
        <!--指定實體類的位置-->
        <property name="packagesToScan"  value="com.qy.domain"/>
       <!-- <property name="annotatedClasses">
            <list>
                <value>com.qy.domain.Province</value>
            </list>
        </property>-->
        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.MySQLDialect
                hibernate.show_sql=true
                hibernate.format_sql=true
                <!--  hibernate.hbm2ddl.auto=create -->
            </value>
        </property>
    </bean>

總結

專案執行時,先讀取web.xml檔案,根據web.xml讀取到applicationContext.xml和springmvc-servlet.xml檔案,在springmvc-servlet檔案主要配置view層的東西,檢視解析器,返回json字串亂碼問題,檔案上傳,定義註解掃描的包,這裡只掃描controller層。applicationContext.xml中也要開始註解掃面,掃描的是除了controller層的其他層。讀取db.properties配置檔案,配置Hibernate的sessionFacory,替代hibernate.cfg.xml檔案,最後是配置事務的屬性,切入點。這樣框架就可以執行起來。可以在seivice層或者test中測試。