Spring5+SpringMvc+Hibernate5整合


Spring5+SpringMvc+Hibernate5整合

​ 在進行環境搭建的時候我發現國內的Spring+SpringMvc+Hibernate整合資料比較少,即使有的話要么就是將所有配置放在一個配置文件,不易於理解結構,要么就是版本太舊,因此這篇文章簡單講解了如何配置相關的開發環境,使用的版本為jdk1.8+spring5+hibernate5

1 分層整合

我們都知道在Spring可以通過<import>標簽來將不同的配置文件進行整合的,因此我們就用這個思路來進行整合,我們將全部的配置文件分為dao層,service層和view層,這樣整合起來比較方便,也比較容易懂

2 創建項目引入依賴

我們首先創建一個名字為Spring5+SpringMvc+Hibernate5的項目,從原型中找到如下的選項

idea給我們創建的項目默認是不完整的

少了一些文件,我們只需要在src上右鍵,選擇創建對應的文件夾即可


有些低版本的idea可能沒有這么只能,你只能手動創建並設置資源和源碼目錄

創建好了之后我們就可以修改一些pom文件中的配置了,以下的文件可以根據自己的情況進行修改

2.1 引入依賴

  • spring依賴
<!--spring依賴-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.0.RELEASE</version>
    <scope>provided</scope>
</dependency>
  • hibernate依賴
<!-- hibernate核心依賴-->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.2.17.Final</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.2.0.Final</version>
</dependency>
  • 數據庫和連接池依賴
<!--連接池依賴-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
</dependency>

<!-- 數據庫依賴 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.12</version>
</dependency>
  • 引入jsp
<!-- jsp依賴 -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.1</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

jsp其實不是必須,但是你如果需要用到進行不分離的開發,那么該依賴最好還是引入一下

其他的依賴可以根據自己的情況引入

2.2 構建配置修改

在build的時候有可能會出現靜態資源沒有build的情況,因此可以采用以下方法

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
                <include>**/*.properties</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.xml</include>
                <include>**/*.properties</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
    .......
</build>

3 准備數據庫

我們在這里准備一個名字為hibernate的數據庫,請自行創建,至於數據庫表我們則不需要創建

4 配置dao層

我們首先在resources下准備一個db-mysql.properties文件,內容如下

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/hibernate?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456

請根據自己的數據庫版本和配置進行書寫,當然這一步不是必須的,但是為了方便找到對應配置項,你可准備這個文件

好了我們可以開始進行spring的配置了,在resources文件夾下創建一個spring-dao,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: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.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
       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.fzu.pojo"></context:component-scan>

    <!-- 加載配置文件-->
    <context:property-placeholder location="classpath:db-mysql.properties"></context:property-placeholder>
    <!-- 配置數據源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close" lazy-init="false">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />

        <property name="initialSize" value="1" />
        <property name="maxActive" value="50" />
        <property name="maxWait" value="30000" />
        <property name="filters" value="stat,wall" />
        <property name="timeBetweenEvictionRunsMillis" value="3000" />
        <property name="minEvictableIdleTimeMillis" value="300000" />
        <property name="validationQuery" value="SELECT 'x'" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <property name="poolPreparedStatements" value="true" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
    </bean>

    <!--配置sessionFactory-->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="packagesToScan" value="com.fzu.pojo"></property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL55Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
    </bean>
    <!-- 配置事務管理-->
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- 開啟注解事務管理 -->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

    <!--配置hibernatetemplate-->
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    
</beans>

請根據自己的情況創建對應的包和選擇相應的屬性例如數據庫方言,我這里是選擇了com.fzu.pojo下存放實體類,我創建了一個Student實體類,其中關於hibernate注解的內容我們不贅述

package com.fzu.pojo;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
public class Student {


    @Id
    private Long studentid;
    private String name;
    private Integer age;
    // 這里請不要用desc,這個是mysql保留字
    private String description;

    @Override
    public String toString() {
        return "Student{" +
                "studentid=" + studentid +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", description='" + description + '\'' +
                '}';
    }

    public Long getStudentid() {
        return studentid;
    }

    public void setStudentid(Long studentid) {
        this.studentid = studentid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

最后在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: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.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
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 開啟注解掃描-->
    <context:component-scan base-package="com.fzu">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <context:annotation-config></context:annotation-config>
    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-mvc.xml"/>
</beans>

由於這里我們service層的內容比較少我們就不單獨創建一個配置文件了

5 配置mvc層

創建spring-mvc.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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/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/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--注解驅動-->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!--過濾靜態資源 -->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>

    <!--掃描controller-->
    <context:component-scan base-package="com.fzu.controller"></context:component-scan>

    <!--視圖解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

其中視圖解析器路徑和掃描的包可以自行確定,不要忘記在applicationContext.xml中引入

6 配置web.xml

我們需要在web.xml中配置spring容器,視圖servlet和編碼servlet

<?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_4_0.xsd"
         version="4.0">

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

    <!-- 配置請求分發器 -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 配置字符過濾器 -->
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 監聽spring容器自動啟動 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 配置session過期時間-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

在創建完相應的類之后,請不要忘記配置tomcat服務器,再啟動之后我們就可以看到相應的表創建了

7 總結

我們首先看一下最后的文件結構

可以看到我們的整個配置過程是模塊化的,從dao層往上,每一層都可以單獨拆裝,除此之外我們項進行其他配置也是很簡單的,例如如果我們想要新增一個redis配置

我們可以按照如下步驟

  • 引入相關依賴
  • 創建db-redis.properties配置文件
  • 創建spring-redis.xml配置文件並進行配置
  • 在applicationContext中引入即可

可以看到整個過程邏輯很清晰


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM