mybatis-plus快速入門並使用


mybatis-plus的初次使用總結

說明:官網自有黃金屋,深入學習看官網是必須的,廢話不多說

環境:springboot、mysql

一、配置

pom

<!--不必多說。geter、setter-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<!--mp依賴-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.0</version>
</dependency>
<!--mp的代碼生成器-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.4.0</version>
</dependency>
<!--mp代碼生成器使用模板-->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.30</version>
</dependency>

yml配置數據庫

#MP配置
#mapper的xml文件的掃描路徑
mybatis-plus:
  mapper-locations: classpath:mapper/**/*Mapper.xml
  type-aliases-package: com.zs.demo.domain
  global-config:
    db-config:
      #配置邏輯刪除字段為0是未刪除
      logic-not-delete-value: 0
      #配置邏輯刪除字段為1是刪除
      logic-delete-value: 1
  #打印sql語句
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

二、代碼生成器

生成效果

配置類,直接運行即可

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

// 演示例子,執行 main 方法控制台輸入模塊表名回車自動生成對應項目目錄中
public class CodeGenerator {

    /**
     * <p>
     * 讀取控制台內容
     * </p>
     */
    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.isNotBlank(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("jobob");
        gc.setOpen(false);
        // gc.setSwagger2(true); 實體屬性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 數據源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/數據庫名?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowMultiQueries=true");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("用戶名");
        dsc.setPassword("密碼");
        mpg.setDataSource(dsc);

        // 包配置=》生成的文件放在該路徑路徑
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模塊名"));
        pc.setParent("com.lrk.gzmhostsystem");
        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("調用默認方法創建的目錄,自定義目錄用");
                if (fileType == FileType.MAPPER) {
                    // 已經生成 mapper 文件判斷存在,不想重新生成返回 false
                    return !new File(filePath).exists();
                }
                // 允許生成模板文件
                return true;
            }
        });
        */
        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("你自己的父類實體,沒有就不用設置!");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父類
//        strategy.setSuperControllerClass("你自己的父類控制器,沒有就不用設置!");
        // 寫於父類中的公共字段
//        strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多個英文逗號分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
//        strategy.setTablePrefix(pc.getModuleName() + "_");
//      忽略數據庫表前綴
        strategy.setTablePrefix("前綴_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}

三、CRUD

 @Autowired
    private IProjectService projectService;
    //查留在下邊分頁位置
    //新增或修改
     boolean flag = projectService.saveOrUpdate(record);
    //boolean flag = projectService.saveOrUpdateBatch(Arrays.asList(record)); 批量操作
    //刪除
     boolean flag = projectService.removeById(record.getId());

四、分頁插件

官網案例

//Spring boot方式
@Configuration
@MapperScan("com.baomidou.cloud.service.*.mapper*")
public class MybatisPlusConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 設置請求的頁面大於最大頁后操作, true調回到首頁,false 繼續請求  默認false
        // paginationInterceptor.setOverflow(false);
        // 設置最大單頁限制數量,默認 500 條,-1 不受限制
        // paginationInterceptor.setLimit(500);
        // 開啟 count 的 join 優化,只針對部分 left join
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }
}

然后發現發現並不好使,PaginationInterceptor 不再被支持。所以改為如下
但是setUseDeprecatedExecutor也只是臨時支持,下一版本會去掉。。。那就再說吧,反正會多表查,不一定會大面積使用mp分頁插件

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

//Spring boot方式
@Configuration
@MapperScan("com.lrk.gzmhostsystem.*.mapper*")
public class MybatisPlusConfig {

   /*  舊版本配置
   @Bean
   public PaginationInterceptor paginationInterceptor(){
      return new PaginationInterceptor();
   }*/

    /**
     * 新的分頁插件,一緩和二緩遵循mybatis的規則,需要設置 MybatisConfiguration#useDeprecatedExecutor = false 避免緩存出現問題
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }
} 

使用分頁插件

  QueryWrapper<Project> queryWrapper = new QueryWrapper<>();
            queryWrapper.like(StringUtils.isNotEmpty(record.getProjectNumber()),"project_number", record.getProjectNumber());

            queryWrapper.orderByDesc("id");
            //分頁查詢
            Page<Project> page = new Page<>(pageNumber, pageSize);
            IPage<Project> iPage = projectService.page(page, queryWrapper);

           System.out.println("當前頁碼:" + iPage.getCurrent());
            System.out.println("每頁顯示數量:" + iPage.getSize());
            System.out.println("總記錄數:" + iPage.getTotal());
            System.out.println("總頁數:" + iPage.getPages());
            List<Project> employeeList = iPage.getRecords();//員工數據集合
            for (Project employee : employeeList) {
                System.out.println(employee);
            }

五、邏輯刪除

步驟1: 配置application.yml

mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: flag  # 全局邏輯刪除的實體字段名(since 3.3.0,配置后可以忽略不配置步驟2)
      logic-delete-value: 1 # 邏輯已刪除值(默認為 1)
      logic-not-delete-value: 0 # 邏輯未刪除值(默認為 0)

步驟2: 實體類字段上加上@TableLogic注解

@TableLogic
private Integer deleted;

六、自動插入創建時間修改時間 即自動填充功能

在實體類中配置屬性創建時間和更新時間,屬性上加入@TableField注解

/**
 * 創建時間
 */
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;

/**
 * 修改時間
 */
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;

注解@TableField中fill詳細介紹

public enum FieldFill {
    /**
     * 默認不處理
     */
    DEFAULT,
    /**
     * 插入填充字段
     */
    INSERT,
    /**
     * 更新填充字段
     */
    UPDATE,
    /**
     * 插入和更新填充字段
     */
    INSERT_UPDATE
}

增加配置文件:編寫處理器Handler來進行自動填充

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
   
/**
 * @program: our-task
 * @description: 對數據庫每條記錄的創建時間和更新時間自動進行填充
 * @author: water76016
 * @create: 2020-11-24 10:53
 **/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入時的填充策略
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推薦使用)
    }
   
    /**
     * 更新時的填充策略
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推薦)
    }
}

注意事項:
填充原理是直接給entity的屬性設置值!!!
注解則是指定該屬性在對應情況下必有值,如果無值則入庫會是null
MetaObjectHandler提供的默認方法的策略均為:如果屬性有值則不覆蓋,如果填充值為null則不填充
字段必須聲明TableField注解,屬性fill選擇對應策略,該聲明告知Mybatis-Plus需要預留注入SQL字段
填充處理器MyMetaObjectHandler在 Spring Boot 中需要聲明@Component或@Bean注入
要想根據注解FieldFill.xxx和字段名以及字段類型來區分必須使用父類的strictInsertFill或者strictUpdateFill方法
不需要根據任何來區分可以使用父類的fillStrategy方法

七、關於時間Date,格式后端與前端保持一致

/**
 * 開始時間
 */
@DateTimeFormat(pattern="yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd")
private Date startTime;

/**
 * 結束時間
 */
@DateTimeFormat(pattern="yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd")
private Date endTime;

data向后端傳輸是字符串年月日格式

<div class="form-group">
    <label for="startTime">開始時間</label>
    <input type="date" class="form-control" id="startTime" name="startTime">
</div>
<div class="form-group">
    <label for="endTime">結束時間</label>
    <input type="date" class="form-control" id="endTime" name="endTime">
</div>

附上經常使用的js工具類(根據input的name數據回顯)

Date.prototype.format = function(fmt)
{
    var o = {
        "M+" : this.getMonth()+1, //月份
        "d+" : this.getDate(), //日
        "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小時
        "H+" : this.getHours(), //小時
        "m+" : this.getMinutes(), //分
        "s+" : this.getSeconds(), //秒
        "q+" : Math.floor((this.getMonth()+3)/3), //季度
        "S" : this.getMilliseconds() //毫秒
    };
    if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
}


function setFormJsonData(obj) {
    var key, value, tagName, type, arr, clas;

    for (x in obj) {

        key = x;

        value = obj[x];

        $("[name='" + key + "'],[name='" + key + "[]']").each(function () {

            tagName = $(this)[0].tagName;

            type = $(this).attr('type');
            clas = $(this).attr('class');
            if (clas != undefined && clas.indexOf("selectpicker") != -1) {
                return;
            }
            if (tagName == 'INPUT') {

                if (type == 'radio') {

                    $(this).attr('checked', $(this).val() == value);

                } else if (type == 'checkbox') {

                    arr = value.split(',');

                    for (var i = 0; i < arr.length; i++) {

                        if ($(this).val() == arr[i]) {

                            $(this).attr('checked', true);

                            break;

                        }
                    }

                } else if (type == 'date') {
                    $(this).val(new Date(value).format("yyyy-MM-dd"));
                } else {
                    $(this).val(value);
                }

            } else if (tagName == 'SELECT' || tagName == 'TEXTAREA') {
                $(this).val(value);
            }
        });

    }
}
<!--調用-->
new Date(value).format("yyyy-MM-dd");
setFormJsonData(row);

官網demo集合,可自行去碼雲查閱,如下

MyBatis-Plus Samples
Build Status codecov

本工程為 MyBatis-Plus 的官方示例,項目結構如下:

mybatis-plus-sample-quickstart: 快速開始示例

mybatis-plus-sample-quickstart-springmvc: 快速開始示例(Spring MVC版本)

mybatis-plus-sample-reduce-springmvc: 簡化掉默認mapper類示例(Spring MVC版本)

mybatis-plus-sample-generator: 代碼生成器示例

mybatis-plus-sample-crud: 完整 CRUD 示例

mybatis-plus-sample-wrapper: 條件構造器示例

mybatis-plus-sample-pagination: 分頁功能示例

mybatis-plus-sample-active-record: ActiveRecord示例

mybatis-plus-sample-sequence: Sequence示例

mybatis-plus-sample-execution-analysis: Sql執行分析示例

mybatis-plus-sample-performance-analysis: 性能分析示例

mybatis-plus-sample-optimistic-locker: 樂觀鎖示例

mybatis-plus-sample-sql-injector: 自定義全局操作示例

mybatis-plus-sample-auto-fill-metainfo: 公共字段填充示例

mybatis-plus-sample-logic-delete: 邏輯刪除示例

mybatis-plus-sample-multi-datasource: 多數據源示例

mybatis-plus-sample-enum: 枚舉注入示例

mybatis-plus-sample-dynamic-tablename: 動態表名示例

mybatis-plus-sample-tenant: 多租戶示例

mybatis-plus-sample-typehandler: 類型處理器示例,例如 json 字段對象轉換

mybatis-plus-sample-deluxe:完整示例(包含分頁、邏輯刪除、自定義全局操作等絕大部分常用功能的使用示例,相當於大整合的完整示例)

mybatis-plus-sample-assembly: 分離打包示例

mybatis-plus-sample-resultmap: 使用 resultMap 示例

mybatis-plus-sample-id-generator: 自定義ID生成示例

mybatis-plus-sample-no-spring: 不使用spring下的示例

mybatis-plus-sample-pagehelper: 使用pagehelper進行分頁

喜歡就關注我吧,我會努力更新的!
公眾號


免責聲明!

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



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