1. 程式人生 > >Spring boot 整合 ssm(spring、spring MVC、Mybatis)

Spring boot 整合 ssm(spring、spring MVC、Mybatis)

Spring boot 簡介:

    1.內建了tomcat, 主語內部整合 ssm打包是一個war包 web工程,boot是jar包,就是一個主函式執行。

    2.配置簡化

      boot是一種主流的微服務的實現。

    3.boot的使用:建議前後端分離使用,沒有分離的不建議使用

spring boot 整合ssm:

1.可以到https://start.spring.io下建立springboot專案:

也可以自己在工具中手動建立,個人感覺這樣比較好用。

2.專案匯入後會缺少一些需要使用的包包,需要自己新增,pom配置如下,後期有需要的包再引入:

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ruifeng</groupId>
    <artifactId>mam</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>mam</name>
    <description>M</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <fastjson.version>1.2.12</fastjson.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.18</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.6</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>${basedir}/src/main/resources</directory>
                <includes>
                    <!--<include>contexts/</include>-->
                    <!--<include>*.xml</include>-->
                    <include>*.yml</include>
                    <include>*.properties</include>
                    <include>*.xml</include>
                    <include>enc_pri</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


3.application-dev.yml配置(資料庫相關)需要注意yml檔案的縮排:

spring:
  datasource:
    name: server
    url: jdbc:mysql://localhost:3306/mamabike
    username: root
    password: root

3.1.application.yml配置:

#server
server:
  port: 80

#spring
spring:
  application:
    name: mamabike
  profiles:
    active: dev #此處映入上面sql的配置資訊


  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    filters: stat
    maxActive: 20
    initialSize: 1
    maxWait: 60000
    minIdle: 1
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxOpenPreparedStatements: 20

#mybatis xml path 包掃描
mybatis:
  mapper-locations: classpath:com/ruifeng/**/**.xml
  type-aliases-package: classpath:com.ruifeng.**.entity

4.然後可以使用generator生成dao、entity:

    4.1.generatorConfig.xml配置:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>

    <!--classPathEntry:資料庫的JDBC驅動 -->
    <!--這裡是maven倉庫中mysql-connector-java-5.1.35.jar的路徑-->
    <classPathEntry
            location="E:\myWork\server\mvnPro\mysql\mysql-connector-java\5.1.35\mysql-connector-java-5.1.35.jar" />

    <context id="MysqlTables" targetRuntime="MyBatis3">

        <!-- 注意這裡面的順序確定的,不能隨變更改 -->
        <!-- 自定義的分頁外掛 <plugin type="com.deppon.foss.module.helloworld.shared.PaginationPlugin"/> -->

        <!-- 可選的(0 or 1) -->
        <!-- 註釋生成器 -->
        <commentGenerator>
            <!-- 是否去除自動生成的註釋 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

        <!-- 必須的(1 required) -->
        <!--資料庫連線的資訊:驅動類、連線地址、使用者名稱、密碼 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mamabike"
                        userId="root" password="123456">
        </jdbcConnection>

        <!-- 可選的(0 or 1) -->
        <!-- 型別轉換器或者加型別解析器 -->
        <!-- 預設false,把JDBC DECIMAL 和 NUMERIC 型別解析為 Integer true,把JDBC DECIMAL 和
            NUMERIC 型別解析為java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>


        <!-- 必須的(1 required) -->
        <!-- java模型生成器 -->
        <!-- targetProject:自動生成程式碼的位置 -->
        <javaModelGenerator targetPackage="com.ruifeng.mam.user.entity"
                            targetProject="C:\Users\Administrator\Desktop\mam\src\main\java"
                             >
            <!-- TODO enableSubPackages:是否讓schema作為包的字尾 -->
            <property name="enableSubPackages" value="true" />
            <!-- 從資料庫返回的值被清理前後的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- 必須的(1 required) -->
        <!-- map xml 生成器 -->
        <sqlMapGenerator targetPackage="com.ruifeng.mam.user.dao"
                         targetProject="C:\Users\Administrator\Desktop\mam\src\main\java">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!-- 可選的(0 or 1) -->
        <!-- mapper 或者就是dao介面生成器 -->
        <javaClientGenerator targetPackage="com.ruifeng.mam.user.dao"
                             targetProject="C:\Users\Administrator\Desktop\mam\src\main\java"
                             type="XMLMAPPER">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!-- 必須的(1...N) -->
        <!-- pojo 實體生成器 -->
        <!-- tableName:用於自動生成程式碼的資料庫表;domainObjectName:對應於資料庫表的javaBean類名 -->
        <!-- schema即為資料庫名 可不寫 -->
        <table  tableName="user" domainObjectName="User"
               enableInsert="true" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
                enableSelectByExample="false" selectByExampleQueryId="false">
            <!-- 忽略欄位 可選的(0 or 1) -->
            <!-- <ignoreColumn column="is_use" /> -->
            <!--//無論欄位是什麼型別,生成的類屬性都是varchar。 可選的(0 or 1) 測試無效 -->
            <!-- <columnOverride column="city_code" jdbcType="VARCHAR" /> -->
        </table>
    </context>
</generatorConfiguration>

我這裡使用的是IDEA編輯的,然後附上生成步驟:

5.簡單的寫一個controller:

package com.ruifeng.mamabike.user.controller;

import com.ruifeng.mamabike.user.dao.UserMapper;
import com.ruifeng.mamabike.user.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("user")
public class UserController {
    //注入mapper
    @Resource
    private UserMapper userMapper;


    @RequestMapping("/hello")
    public User hello(){
        User user = userMapper.selectByPrimaryKey(1l);//根據主鍵去查詢user物件
        return user;
    }

}

6.最後直接執行主類main方法就搞定了:

package com.ruifeng.mamabike;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
public class MamabikeApplication {

    /**
     * spring boot專案入口
     * @param args
     */
	public static void main(String[] args) {

	    SpringApplication.run(MamabikeApplication.class, args);
	}
}

成功頁面:

如果出現userMapper注入失敗的錯誤,可以在UserMapper介面上使用@Mapper來解決。