SSM(Spring+SpringMVC+Mybatis)框架搭建詳細教程【附原始碼Git】

weixin_33866037發表於2017-10-30

一個從零開始的SSM框架Demo對一個新手來說,是非常重要的,可大大減少在學習過程中遇到的各種各樣的坑,說到最後,也算是助人為樂吧!下面我們從零開始進行SSM框架的搭建,在介紹最後,我會把專案部署在GitHub以便需要Demo的親朋好友們進行下載~~~
開源git地址:https://github.com/yonghu86/SSM-Demo
本Demo是在IDEA下搭建的Maven專案,在進行下面閱讀前先了解這一點!
【開發環境】
  1.作業系統:Windows7 ×64 Sp1
  

1459766-fbe206051c527ff7.png
作業系統

  2.Java-Version:1.8.0_101
  
1459766-be6dbb60223d4261.png

  3.IDE:IntelliJ IDEA 2017.2.2 x64
  
1459766-37a000d6defbed98.png

一、新建專案
  執行IDEA,進入初始化介面,然後我們選擇新建專案(進入主介面新建專案也是一樣的)
  
1459766-ec0d6f53244836c9.png

  在Maven選項卡里面找到對應的java web選項,然後我們點下一步
  
1459766-22804a864fdad538.png

  這一步填入組織等資訊,這裡比較隨意,按照自己的需求進行填寫,然後下一步
  
1459766-8651f00babbd445d.png

  這裡我早已配置好本地Maven倉庫,因此直接預設即可。如果沒進行配置本地預設倉庫的話,請網上查詢對應的資料進行配置
  
1459766-39c888cc53e17042.png

  輸入Project name,和需要儲存的路徑,然後finish
  
1459766-0b4a488c92a49c8c.png

  去泡一杯咖啡吧,這裡需要一小段時間哦~
  稍等片刻,idea已經為我們自動建好了一切。到這裡,我們的第一步,新建專案階段已經完成,歡慶一下,進入下一個階段。
  
1459766-b9054150187c23e3.png

  新建好專案後,我們首先開啟SSM_Demo,修改一下JDK版本。
  
1459766-183b60ba32e87dd2.png

  
1459766-433073fd7888833b.png

  在settings裡面對專案版本進行修改:
  
1459766-03fb350e23ca49e9.png

  原來是1_5,現在改為1_8,可能會存在spring等框架版本和jdk版本不相容問題,因此,提前升級了版本。
二、目錄結構調整
首先我們配置Maven的專案結構,選擇Project Structure
  
1459766-a85af6e434fdb524.png

  選擇Modules標籤頁,然後新建並標識對應的專案結構
1459766-ee56924781a97994.png

  最終的檔案結構如下所示:
  
1459766-d95a6791bf49e6d7.png

  
1459766-a909f36fef0ba4a5.png

  - Java為主Java程式碼資料夾
    - Controllers 控制器檔案資料夾
    - Dao (資料訪問)層資料夾
    - Service(業務邏輯)層資料夾
    - Entity(實體)層資料夾
  - resources資原始檔夾
    - mapper mybatis sql資料夾
  - webapp web頁面資料夾
  - Test 測試資料夾
三、Maven包的初始化
Maven是採用配置檔案的方式進行jar包的自動匯入,因此,我們需要進行對配置檔案的修改來進行jar包的匯入。
  開啟pom.xml檔案
  
1459766-61ba4b9a601fa074.png

  新增我們將會用到的一系列jar包配置(這裡將我的配置直接複製過來,作為參考)

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>QX_JFrame</groupId>
  <artifactId>Demo</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>Demo Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <!--Unit Test - 單元測試-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
    <!--Spring-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.3.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>4.3.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.3.5.RELEASE</version>
    </dependency>
    <!--Spring transaction-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-mock</artifactId>
      <version>2.0.8</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>4.3.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>4.3.5.RELEASE</version>
    </dependency>
    <!--Spring Web + Spring MVC-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>3.7.3</version>
    </dependency>
    <dependency>
      <groupId>com.github.jsqlparser</groupId>
      <artifactId>jsqlparser</artifactId>
      <version>0.9.1</version>
    </dependency>
    <!--mysql jdbc-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>
    <!--c3p0-->
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
    </dependency>
    <!--NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config-->
    <!-- https://mvnrepository.com/artifact/jstl/jstl -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!--file upload jar package-->
    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>
    <!--json-->
    <!-- https://mvnrepository.com/artifact/org.json/json -->
    <dependency>
      <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>20160212</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>2.4</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.6</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
    <dependency>
      <groupId>commons-beanutils</groupId>
      <artifactId>commons-beanutils</artifactId>
      <version>1.8.3</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
    <dependency>
      <groupId>commons-collections</groupId>
      <artifactId>commons-collections</artifactId>
      <version>3.2.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/net.sf.ezmorph/ezmorph -->
    <dependency>
      <groupId>net.sf.ezmorph</groupId>
      <artifactId>ezmorph</artifactId>
      <version>1.0.6</version>
    </dependency>
    <!--json serialize and deserialization-->
    <!-- 引入fastjson依賴 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.12</version>
    </dependency>
    <!-- 引入gson依賴 -->
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.6.2</version>
    </dependency>
    <!--Base64 加解密-->
    <!-- https://mvnrepository.com/artifact/net.iharder/base64 -->
    <dependency>
      <groupId>net.iharder</groupId>
      <artifactId>base64</artifactId>
      <version>2.3.8</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.10</version>
    </dependency>
    <!--log4j-->
    <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.6.2</version>
    </dependency>
    <dependency>
      <groupId>org.jetbrains</groupId>
      <artifactId>annotations-java5</artifactId>
      <version>RELEASE</version>
    </dependency>
    <!--mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.0</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.3</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>Demo</finalName>
  </build>
</project>

待配置好的jar包都自動下載並匯入後,我們maven包的匯入階段就完成了,下面我們開始整合各個元件。
四、Spring MVC的配置
  在resources資原始檔夾下新建spring-servlet.xml檔案,並在配置檔案中宣告spring mvc框架對控制器、頁面、資源的訪問

  
1459766-e02695ca1d65cea7.png

  在其中新增下面配置標籤資訊:
<?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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

    <!-- 啟動註解驅動的Spring MVC功能,註冊請求url和註解POJO類方法的對映-->
    <mvc:annotation-driven >

    </mvc:annotation-driven>

    <!-- 啟動包掃描功能,以便註冊帶有@Controllers、@service、@repository、@Component等註解的類成為spring的bean -->
    <context:component-scan base-package="Controllers" />
    <!-- 對模型檢視名稱的解析,在請求時模型檢視名稱新增前字尾 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/"/>    <!-- 字首 -->
        <property name="suffix" value=".jsp"/>    <!-- 字尾 -->
    </bean>
    <!-- 訪問靜態檔案(jpg,js,css)的方法 -->
    <!--<mvc:resources location="/files/" mapping="/files/**" />-->
    <!--<mvc:resources location="/scripts/" mapping="/scripts/**" />-->
    <!--<mvc:resources location="/styles/" mapping="/styles/**" />-->
    <!--<mvc:resources location="/Views/" mapping="/Views/**" />-->
</beans>

1459766-27e1bd4ed8508284.png

  這裡的Controllers對應的是我們之前新建好的Controllers包資料夾。
  對web.xml進行配置,將我們剛才新增的spring-servlet.xml配置進去
  
1459766-3725c2eb3b7a473b.png

  
1459766-9557b01038190bb6.png

  這裡的classpath為resources資源目錄
  這一步配置的web.xml內容如下:

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
  <display-name>Archetype Created Web Application</display-name>
  <welcome-file-list>
    <welcome-file>/index.jsp</welcome-file>
  </welcome-file-list>
  <!-- Spring MVC配置 -->
  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--Spring-servlet.xml config-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-servlet.xml</param-value>
    </init-param>
    <!-- load-on-startup元素標記容器是否在啟動的時候就載入這個servlet(例項化並呼叫其init()方法) -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>
我們新建一個控制器測試一下(在Controllers包新建java類,RequestTestController):
1459766-855fb673e05d3218.png

  接下來在RequestTestController裡面寫一個rest api介面:

  
1459766-c7838bba147e3403.png

  介面程式碼如下:

package Controllers;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/RequestTest")
public class RequestTestController {

    @GetMapping()
    public String TestString(){
        return "this is a test string. Time:2017-10-29 20:42:00";
    }
}

這樣,我們便可以通過url地址來進行訪問我們的介面資料
  

1459766-2f78c11699fc7fcf.png

  在右上角的執行伺服器配置按鈕,開啟伺服器配置項
  
1459766-285e28e1e008318f.png

  這裡如果左側列表是空的話,我們就需要點選加號進行伺服器的新增,選擇Tomcat Server下的Local。然後點選剛剛新增的標籤,在右側輸入Server Name,下面會自動提示設定編譯方式,選一個編譯方式,然後點選OK即可(這一步的前提是裝好了Tomcat伺服器,如果沒有安裝,則需要先安裝Tomcat伺服器)。
  然後我們點選右上角的執行,如果沒有什麼問題的話,我們的控制檯介面會提示服務啟動成功!(我這樣下來是不會出問題的)
  
1459766-f9799bdc68382350.png

  等瀏覽器開啟以後,我們輸入我們配置的api地址:http://localhost:8080/api/RequestTest
  
1459766-8e53f985f9716fdb.png

  這樣,spring mvc已經成功整合到了專案裡面!
五、Spring和Mybatis的配置
  稍歇片刻後,我們繼續進行Mybatis和Spring元件的整合...
  先新增jdbc.properties(JDBC連線配置檔案,當然這個檔案裡面的內容直接寫到mybatis配置檔案裡面也是可以的)
  
1459766-4dcddd39de109e3f.png

  內容如下:

#mysql
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://***.***.***\:3306/db_test?useSSL=false
jdbc.username=username
jdbc.password=password

#c3p0連線池資訊
c3p0.minPoolSize=10
c3p0.maxPoolSize=100
#當連線池中的連線耗盡的時候c3p0一次同時獲取的連線數
c3p0.acquireIncrement=3
#定義在從資料庫獲取新連線失敗後重復嘗試的次數
c3p0.acquireRetryAttempts=60
#兩次連線中間隔時間,單位毫秒
c3p0.acquireRetryDelay=1000
#連線關閉時預設將所有未提交的操作回滾
c3p0.autoCommitOnClose=false
#當連線池用完時客戶端呼叫getConnection()後等待獲取新連線的時間,超時後將丟擲SQLException,如設為0則無限
c3p0.checkoutTimeout=3000
#每120秒檢查所有連線池中的空閒連線。Default: 0
c3p0.idleConnectionTestPeriod=120
#最大空閒時間,60秒內未使用則連線被丟棄。若為0則永不丟棄。Default: 0
c3p0.maxIdleTime=600
#如果設為true那麼在取得連線的同時將校驗連線的有效性。Default: false
c3p0.testConnectionOnCheckin=false
#如果maxStatements與maxStatementsPerConnection均為0,則快取被關閉。Default: 0
c3p0.maxStatements=8
#maxStatementsPerConnection定義了連線池內單個連線所擁有的最大快取statements數。Default: 0
c3p0.maxStatementsPerConnection=5
#自動超時回收Connection
c3p0.unreturnedConnectionTimeout=25

jdbc.properties

繼續在resources資料夾裡面新增mybatis配置檔案 spring-mybatis.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" 
       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/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="configProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
    </bean>

    <!-- 配置資料來源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClassName}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="minPoolSize" value="${c3p0.minPoolSize}"/>
        <property name="acquireIncrement" value="${c3p0.acquireIncrement}"/>
        <property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
        <property name="acquireRetryDelay" value="${c3p0.acquireRetryDelay}"/>
        <property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
        <property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
        <property name="idleConnectionTestPeriod" value="${c3p0.idleConnectionTestPeriod}"/>
        <property name="maxIdleTime" value="${c3p0.maxIdleTime}"/>
        <property name="testConnectionOnCheckin" value="${c3p0.testConnectionOnCheckin}"/>
        <property name="maxStatements" value="${c3p0.maxStatements}"/>
        <property name="maxStatementsPerConnection" value="${c3p0.maxStatementsPerConnection}"/>
        <property name="unreturnedConnectionTimeout" value="${c3p0.unreturnedConnectionTimeout}"/>
    </bean>

    <!-- 配置mybatisSqlSessionFactoryBean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
    <!-- 配置mybatis mapper介面 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="Dao"/>
        <!--<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>-->
    </bean>

    <!-- 配置事務管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>

spring-mybatis.xml

新增spring支援(applicationContext.xml),並在spring支援裡面將mybatis配置檔案進行引入
  內容如下:

<?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"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config />
    <!-- 配置component所在的包,自動載入需要管理的Bean -->
    <context:component-scan base-package="Service,Dao" />
    <import resource="spring-mybatis.xml" />
</beans>

applicationContext.xml配置檔案是對spring的配置,我們配置spring元件的掃描包圍Service和Dao層目錄,然後將spring-mybatis.xml配置檔案匯入.
  完成這三個後的檔案目錄是這樣子的:

  
1459766-92866e4a59d0a131.png

  target資料夾是剛才編譯執行時候自動產生的,不要驚慌~~~
  完成這幾步後,我們還需要將spring的配置載入到已有的框架中去,開啟web.xml檔案,進行新增spring配置

  在剛才的web-app標籤內繼續新增spring支援:

  
1459766-450355f84b9bc6d4.png

  此刻完整的web.xml檔案內容如下:
<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
  <display-name>Archetype Created Web Application</display-name>
  <welcome-file-list>
    <welcome-file>/index.jsp</welcome-file>
  </welcome-file-list>
  <!-- Spring MVC配置 -->
  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--Spring-servlet.xml config-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-servlet.xml</param-value>
    </init-param>
    <!-- load-on-startup元素標記容器是否在啟動的時候就載入這個servlet(例項化並呼叫其init()方法) -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!--spring listener config-->
  <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>

  <!-- 配置log4j配置檔案的路徑,可以是xml或 properties(此引數必須配)-->
  <!--<context-param>-->
  <!--<param-name>log4jConfigLocation</param-name>-->
  <!--<param-value>classpath:log4j.properties</param-value>-->
  <!--</context-param>-->

</web-app>

web.xml

 到此刻,我們的spring、mybatis已經整合完畢,接下來稍歇片刻,我們進行demo的完成。
六、demo的構建
  開啟資料庫,我們新建一個資料庫,並設計兩張測試表,student和studentclass
  

1459766-18a3bbc526dfe7e8.png

  student表的設計如下:
  
1459766-ec74031ede802a82.png

-- ----------------------------
-- Table structure for `student`
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `Uid` binary(36) NOT NULL COMMENT 'Uid',
  `Name` varchar(20) NOT NULL,
  `Age` int(3) NOT NULL,
  `ClassId` int(3) NOT NULL,
  PRIMARY KEY (`Uid`),
  KEY `StudentClass` (`ClassId`),
  CONSTRAINT `StudentClass` FOREIGN KEY (`ClassId`) REFERENCES `studentclass` (`ClassId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

studentclass表的設計如下:
  

1459766-1c8856483d9cc69f.png

-- ----------------------------
-- Table structure for `studentclass`
-- ----------------------------
DROP TABLE IF EXISTS `studentclass`;
CREATE TABLE `studentclass` (
  `ClassId` int(3) NOT NULL AUTO_INCREMENT,
  `ClassName` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`ClassId`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

將資料庫建好後,我們進行Entity,Dao,Service層以及mapper檔案的的編寫。

首先在mapper資料夾新建一個mapper檔案:StudentMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="Dao.StudentMapper">
    <resultMap id="BaseResultMap" type="Entity.Student">
        <id column="Uid" jdbcType="BINARY" property="uid" />
        <result column="Name" jdbcType="VARCHAR" property="name" />
        <result column="Age" jdbcType="INTEGER" property="age" />
        <result column="ClassId" jdbcType="INTEGER" property="classid" />
    </resultMap>
    <sql id="Base_Column_List">
        Uid, Name, Age, ClassId
    </sql>
    <select id="selectByPrimaryKey" parameterType="byte[]" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from student
        where Uid = #{uid,jdbcType=BINARY}
    </select>
    <select id="selectByCondition" parameterType="Entity.Student" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        from student
        <where>
            1=1
            <if test="uid != null">
                and Uid=#{uid,jdbcType=BINARY}
            </if>
            <if test="name != null">
                and Name=#{name,jdbcType=VARCHAR}
            </if>
            <if test="age != null">
                and Age=#{age,jdbcType=INTEGER}
            </if>
            <if test="classid != null">
                and ClassId=#{classid,jdbcType=INTEGER}
            </if>
        </where>
    </select>
    <delete id="deleteByPrimaryKey" parameterType="byte[]">
        delete from student
        where Uid = #{uid,jdbcType=BINARY}
    </delete>
    <insert id="insert" parameterType="Entity.Student">
        insert into student (Uid, Name, Age,
        ClassId)
        values (#{uid,jdbcType=BINARY}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER},
        #{classid,jdbcType=INTEGER})
    </insert>
    <insert id="insertSelective" parameterType="Entity.Student">
        insert into student
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="uid != null">
                Uid,
            </if>
            <if test="name != null">
                Name,
            </if>
            <if test="age != null">
                Age,
            </if>
            <if test="classid != null">
                ClassId,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="uid != null">
                #{uid,jdbcType=BINARY},
            </if>
            <if test="name != null">
                #{name,jdbcType=VARCHAR},
            </if>
            <if test="age != null">
                #{age,jdbcType=INTEGER},
            </if>
            <if test="classid != null">
                #{classid,jdbcType=INTEGER},
            </if>
        </trim>
    </insert>
    <update id="updateByPrimaryKeySelective" parameterType="Entity.Student">
        update student
        <set>
            <if test="name != null">
                Name = #{name,jdbcType=VARCHAR},
            </if>
            <if test="age != null">
                Age = #{age,jdbcType=INTEGER},
            </if>
            <if test="classid != null">
                ClassId = #{classid,jdbcType=INTEGER},
            </if>
        </set>
        where Uid = #{uid,jdbcType=BINARY}
    </update>
    <update id="updateByPrimaryKey" parameterType="Entity.Student">
        update student
        set Name = #{name,jdbcType=VARCHAR},
        Age = #{age,jdbcType=INTEGER},
        ClassId = #{classid,jdbcType=INTEGER}
        where Uid = #{uid,jdbcType=BINARY}
    </update>
</mapper>

以上這段程式碼是直接使用mybatis generator直接進行生成的,如果不想手寫的話(手寫容易出錯),可以直接使用該工具進行生成
  新增Entity實體

  
1459766-92cb76bcdcf486d2.png
package Entity;

public class Student {
    private byte[] uid;

    private String name;

    private Integer age;

    private Integer classid;

    public byte[] getUid() {
        return uid;
    }

    public void setUid(byte[] uid) {
        this.uid = uid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public Integer getAge() {
        return age;
    }

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

    public Integer getClassid() {
        return classid;
    }

    public void setClassid(Integer classid) {
        this.classid = classid;
    }
}

在Dao層寫Mybatis介面(不需要寫實現類,mybatis不需要),新建StudentMapper

  
1459766-6d2b74710be4ec2c.png
package Dao;

import Entity.Student;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface StudentMapper {
    int deleteByPrimaryKey(byte[] uid);

    int insert(Student record);

    int insertSelective(Student record);

    Student selectByPrimaryKey(byte[] uid);

    List<Student> selectByCondition(Student record);

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);
}

在Service層寫對Dao層的訪問邏輯,當然Demo沒有什麼業務處理邏輯,僅作為Demo
  

1459766-313bc889ab7e5ae3.png

  IStudentService 介面:

package Service;

import Entity.Student;

import java.util.List;

public interface IStudentService {
    int deleteByPrimaryKey(byte[] uid);

    int insert(Student record);

    int insertSelective(Student record);

    Student selectByPrimaryKey(byte[] uid);

    List<Student> selectByCondition(Student record);

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);
}

StudentService 實現了 IStudentService 介面:

package Service;

import Dao.StudentMapper;
import Entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentService implements IStudentService {
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public int deleteByPrimaryKey(byte[] uid) {
        return studentMapper.deleteByPrimaryKey(uid);
    }

    @Override
    public int insert(Student record) {
        return studentMapper.insert(record);
    }

    @Override
    public int insertSelective(Student record) {
        return studentMapper.insertSelective(record);
    }

    @Override
    public Student selectByPrimaryKey(byte[] uid) {
        return studentMapper.selectByPrimaryKey(uid);
    }

    @Override
    public List<Student> selectByCondition(Student record) {
        return studentMapper.selectByCondition(record);
    }

    @Override
    public int updateByPrimaryKeySelective(Student record) {
        return studentMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Student record) {
        return studentMapper.updateByPrimaryKey(record);
    }
}

然後我們寫一個StudentController用於呼叫Service


1459766-f19cefce77dba945.png
package Controllers;

import Entity.Student;
import Service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api/Student")
public class StudentController {
    @Autowired
    private IStudentService service;

    @GetMapping()
    public String Get() {
        List<Student> students = service.selectByCondition(new Student());
        String jsonResult = com.alibaba.fastjson.JSON.toJSONString(students);
        return jsonResult;
    }
}

 走到這一步的程式碼目錄結構是這樣子的:
  

1459766-8914b448d77fd285.png

  如果進行順利的話,我們執行我們的Tomacat伺服器,並呼叫我們的新介面:http://localhost:8080/api/Student
  執行時候,別忘記了修改jdbc.properties檔案裡的連線url以及使用者名稱密碼!!!
  
1459766-393016e3eb52b07e.png

  
1459766-f2d398e28d66a107.png

  哇,資料成功顯示!(別把這個資料當成你會真的顯示出來的一樣,這是我資料庫原有的資料,哈哈哈)
  
1459766-1271ae2e54430a9b.png

  還不快去新增幾條資料呼叫一下試試嘛~
七、結尾
  至此,我們的SSM框架已經基本搭建完畢,我們已經用我們搭建的Demo從真實的資料庫中獲取到了資料,並轉成了Json格式,在瀏覽器中用Rest api介面的形式獲取到了。
  該專案原始碼可以在Github上找到,如果需要的可以直接去下載->
  https://github.com/yonghu86/SSM-Demo (不趕緊訪問點個Star嘛?)****

相關文章