Springboot整合MybatisPlus(超詳細)完整教程~

易水寒的部落格發表於2020-05-27

新建springboot專案

開發工具:idea2019.2,maven3


pom.xml

    <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>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- mybatis plus 程式碼生成器 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

application.yml:

server:
  port: 8081
  servlet:
    context-path: /

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/demo?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
    username: root
    password: lyja
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
    serialization:
      write-dates-as-timestamps: false

mybatis-plus:
  configuration:
    map-underscore-to-camel-case: true
    auto-mapping-behavior: full
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath*:mapper/**/*Mapper.xml
  global-config:
    # 邏輯刪除配置
    db-config:
      # 刪除前
      logic-not-delete-value: 1
      # 刪除後
      logic-delete-value: 0

mybatisplus分頁外掛MybatisPlusConfig:

package com.example.conf;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 配置分頁外掛
 *
 */
@Configuration
public class MybatisPlusConfig {

    /**
     * 分頁外掛
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

mybatisplus自動生成程式碼GeneratorCodeConfig.java:

package com.example.conf;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.Scanner;

/**
 * 自動生成mybatisplus的相關程式碼
 */
public class GeneratorCodeConfig {

    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("請輸入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("請輸入正確的" + tip + "!");
    }

    public static void main(String[] args) {
        // 程式碼生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全域性配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("astupidcoder");
        gc.setOpen(false);
        //實體屬性 Swagger2 註解
        gc.setSwagger2(false);
        mpg.setGlobalConfig(gc);

        // 資料來源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/demo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("lyja");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
//        pc.setModuleName(scanner("模組名"));
        pc.setParent("com.example");
        pc.setEntity("model.auto");
        pc.setMapper("mapper.auto");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        mpg.setPackageInfo(pc);

        // 自定義配置
//        InjectionConfig cfg = new InjectionConfig() {
//            @Override
//            public void initMap() {
//                // to do nothing
//            }
//        };

        // 如果模板引擎是 freemarker
//        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // 自定義輸出配置
//        List<FileOutConfig> focList = new ArrayList<>();
        // 自定義配置會被優先輸出
//        focList.add(new FileOutConfig(templatePath) {
//            @Override
//            public String outputFile(TableInfo tableInfo) {
//                // 自定義輸出檔名 , 如果你 Entity 設定了前字尾、此處注意 xml 的名稱會跟著發生變化!!
//                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
//                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
//            }
//        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判斷自定義資料夾是否需要建立
                checkDir("呼叫預設方法建立的目錄");
                return false;
            }
        });
        */
//        cfg.setFileOutConfigList(focList);
//        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定義輸出模板
        //指定自定義模板路徑,注意不要帶上.ftl/.vm, 會根據使用的模板引擎自動識別
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);

        strategy.setEntityLombokModel(true);
        // 公共父類
//        strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
        // 寫於父類中的公共欄位
//        strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多個英文逗號分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

測試

建表:

執行GeneratorCodeConfig.java檔案,輸入表名user:

解決方法:在資料庫連線中配置新增allowPublicKeyRetrieval=true


檢視生成的檔案;

新增掃描mapper註解

啟動springboot的application啟動類:會報錯,提示找不到mapper檔案,我們需要在springboot啟動類上新增掃描mapper的註解:

package com.example;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.example.mapper")
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

UserController.java中新增介面:

  @Autowired
    private IUserService userService;
    @PostMapping("/getUser")
    public User getUser(){
        return userService.getById(1);
    }

postman測試:


沒問題。

上面是mybatisplus測試成功,下面我們繼續測試我們自己寫的sql是否成功。

在resources目錄下新建mapper資料夾,新建UserMapper.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="com.example.mapper.auto.UserMapper">

    <!-- 查詢使用者資訊 -->
    <select id="findAllUser" resultType="com.example.model.auto.User">
       select * from user
    </select>

</mapper>

UserMapper.java

package com.example.mapper.auto;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.model.auto.User;

import java.util.List;

/**
 * <p>
 *  Mapper 介面
 * </p>
 *
 * @author astupidcoder
 * @since 2020-05-13
 */
public interface UserMapper extends BaseMapper<User> {

    public List<User>findAllUser();
}

IUserService:

package com.example.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.example.model.auto.User;

import java.util.List;

/**
 * <p>
 *  服務類
 * </p>
 *
 * @author astupidcoder
 * @since 2020-05-13
 */
public interface IUserService extends IService<User> {

    public List<User> findAllUser();
}

UseServiceImpl.java:

package com.example.service.impl;

import com.example.model.auto.User;
import com.example.mapper.auto.UserMapper;
import com.example.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服務實現類
 * </p>
 *
 * @author astupidcoder
 * @since 2020-05-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public List<User> findAllUser() {
        return userMapper.findAllUser();
    }
}

UserController.java:

package com.example.controller;


import com.example.model.auto.User;
import com.example.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

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

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author astupidcoder
 * @since 2020-05-13
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;
    @PostMapping("/getUser")
    public User getUser(){
        return userService.getById(1);
    }


    @PostMapping("/findAllUser")
    public List<User> findAllUser(){
        return userService.findAllUser();
    }
}

測試findAllUser介面:

常用的工具類:

ResultInfo.java

package com.example.conf;

import lombok.Data;

import java.io.Serializable;

/**
 *返回結果類統一封裝
 */
@Data
public class ResultInfo implements Serializable {

    // 狀態碼
    private Integer code;
    // 訊息
    private String message;
    // 資料物件
    private Object result;

    private Integer total;

    /**
     * 無參構造器
     */
    public ResultInfo() {
        super();
    }

    public ResultInfo(Status status) {
        super();
        this.code = status.code;
        this.message = status.message;
    }

    public ResultInfo result(Object result) {
        this.result = result;
        return this;
    }

    public ResultInfo message(String message) {
        this.message = message;
        return this;
    }
    public ResultInfo total(Integer total) {
        this.total = total;
        return this;
    }

    /**
     * 只返回狀態,狀態碼,訊息
     *
     * @param code
     * @param message
     */
    public ResultInfo(Integer code, String message) {
        super();
        this.code = code;
        this.message = message;
    }

    /**
     * 只返回狀態,狀態碼,資料物件
     *
     * @param code
     * @param result
     */
    public ResultInfo(Integer code, Object result) {
        super();
        this.code = code;
        this.result = result;
    }

    /**
     * 返回全部資訊即狀態,狀態碼,訊息,資料物件
     *
     * @param code
     * @param message
     * @param result
     */
    public ResultInfo(Integer code, String message, Object result) {
        super();
        this.code = code;
        this.message = message;
        this.result = result;
    }
}

Status.java

package com.example.conf;

/**
 * 列舉類物件
 */
public enum Status {

    // 公共
    SUCCESS(2000, "成功"),
    UNKNOWN_ERROR(9998,"未知異常"),
    SYSTEM_ERROR(9999, "系統異常"),


    INSUFFICIENT_PERMISSION(4003, "許可權不足"),

    WARN(9000, "失敗"),
    REQUEST_PARAMETER_ERROR(1002, "請求引數錯誤"),

    // 登入
    LOGIN_EXPIRE(2001, "未登入或者登入失效"),
    LOGIN_CODE_ERROR(2002, "登入驗證碼錯誤"),
    LOGIN_ERROR(2003, "使用者名稱不存在或密碼錯誤"),
    LOGIN_USER_STATUS_ERROR(2004, "使用者狀態不正確"),
    LOGOUT_ERROR(2005, "退出失敗,token不存在"),
    LOGIN_USER_NOT_EXIST(2006, "該使用者不存在"),
    LOGIN_USER_EXIST(2007, "該使用者已存在");

    public int code;
    public String message;

    Status(int code, String message) {
        this.code = code;
        this.message = message;
    }
}

附錄:

一份詳盡的yml配置檔案(關於資料來源的配置比較詳盡):

server:
  port: 8085
  servlet:
    context-path: /test


spring:
  #redis叢集
  redis:
    host: 127.0.0.1
    port: 6379
    timeout: 20000
    #    叢集環境開啟下面註釋,單機不需要開啟
    #    cluster:
    #      叢集資訊
    #      nodes: xxx.xxx.xxx.xxx:xxxx,xxx.xxx.xxx.xxx:xxxx,xxx.xxx.xxx.xxx:xxxx
    #      #預設值是5 一般當此值設定過大時,容易報:Too many Cluster redirections
    #      maxRedirects: 3
    password: lyja
    application:
      name: test
    jedis:
      pool:
        max-active: 8
        min-idle: 0
        max-idle: 8
        max-wait: -1
    database: 0

  autoconfigure:
    exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
  datasource:
    dynamic:
      #設定預設的資料來源或者資料來源組,預設值即為master
      primary: master
      strict: false
      datasource:
        master:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false
          username: root
          password: lyja
    # 資料來源配置
    druid:
      # druid連線池監控
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        login-username: admin
        login-password: admin
        # 初始化時建立物理連線的個數
        initial-size: 5
        # 最大連線池數量
        max-active: 30
        # 最小連線池數量
        min-idle: 5
        # 獲取連線時最大等待時間,單位毫秒
        max-wait: 60000
        # 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒
        time-between-eviction-runs-millis: 60000
        # 連線保持空閒而不被驅逐的最小時間
        min-evictable-idle-time-millis: 300000
        # 用來檢測連線是否有效的sql,要求是一個查詢語句
        validation-query: select count(*) from dual
        # 建議配置為true,不影響效能,並且保證安全性。申請連線的時候檢測,如果空閒時間大於timeBetweenEvictionRunsMillis,執行validationQuery檢測連線是否有效。
        test-while-idle: true
        # 申請連線時執行validationQuery檢測連線是否有效,做了這個配置會降低效能。
        test-on-borrow: false
        # 歸還連線時執行validationQuery檢測連線是否有效,做了這個配置會降低效能。
        test-on-return: false
        # 是否快取preparedStatement,也就是PSCache。PSCache對支援遊標的資料庫效能提升巨大,比如說oracle。在mysql下建議關閉。
        pool-prepared-statements: false
        # 要啟用PSCache,必須配置大於0,當大於0時,poolPreparedStatements自動觸發修改為true。
        max-pool-prepared-statement-per-connection-size: 50
        # 配置監控統計攔截的filters,去掉後監控介面sql無法統計
        filters: stat,wall
        # 通過connectProperties屬性來開啟mergeSql功能;慢SQL記錄
        connection-properties:
          druid.stat.mergeSql: true
          druid.stat.slowSqlMillis: 500
        # 合併多個DruidDataSource的監控資料
        use-global-data-source-stat: true
        filter:
          stat:
            log-slow-sql: true
            slow-sql-millis: 1000
            merge-sql: true
          wall:
            config:
              multi-statement-allow: true
  servlet:
    multipart:
      # 開啟 multipart 上傳功能
      enabled: true
      # 檔案寫入磁碟的閾值
      file-size-threshold: 2KB
      # 最大檔案大小
      max-file-size: 200MB
      # 最大請求大小
      max-request-size: 215MB

mybatis-plus:
  configuration:
    map-underscore-to-camel-case: true
    auto-mapping-behavior: full
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath*:mapper/**/*Mapper.xml
  global-config:
    # 邏輯刪除配置
    db-config:
      # 刪除前
      logic-not-delete-value: 1
      # 刪除後
      logic-delete-value: 0
logging:
  level:
    root: info
    com.example: debug

相關文章