Spring boot integrates mybatis plus


1 Introduction to mybatis plus

Mybatis- plus is a powerful and enhanced toolkit for mybatis to simplify development. The toolkit provides mybatis with some efficient, useful and out of the box features, which can effectively save development time.

1.1 advantages

  1. Mybatis plus provides interfaces such as basic addition, deletion, modification and query, and paging query, which can effectively simplify development and improve development efficiency. Especially in the background management system, operation system and other scenarios, mybatis plus is particularly suitable for development.
  2. The built-in code generator is also very easy to use, which can quickly generate mapper java、Mapper. XML, Dao, service and controller layer code.
  3. Support multiple databases: support mysql, Oracle, DB2, H2, hsql, SQLite, PostgreSQL, sqlserver, Phoenix, Gauss, Clickhouse, Sybase, oceanbase, Firebird, cubrid, Goldilocks, csiidb and other databases

2 spring boot integration with mybatis plus

2.1 import POM dependency



PS: you can modify the version by yourself.

2.2 configuration database YML

    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
    type: com.alibaba.druid.pool.DruidDataSource

# Logger Config
    com.baomidou.mybatisplus.samples: debug

2.3 add config file

public class MybatisPlusConfig {


Ps: if paging is required, add paging configuration

//Old edition
//    @Bean
//    public PaginationInterceptor paginationInterceptor() {
//        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
//// set the requested page to be larger than the maximum page. True will call back to the home page. False will continue to request. The default is false
//        // paginationInterceptor.setOverflow(false);
//// set the maximum number of single page restrictions. The default number is 500, -1 is unlimited
//        // paginationInterceptor.setLimit(500);
//// enable the join optimization of count, only for some left joins
//        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
//        return paginationInterceptor;
//    }
//Latest edition
public MybatisPlusInterceptor mybatisPlusInterceptor() {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
    return interceptor;

2.4 integrated code generator

Import POM package


Code generation class

package com.prepared;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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 java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

//Demo example: execute the main method console to input the module table name and press enter to automatically generate the corresponding project directory
public class CodeGenerator {

     * <p>
     *Read console contents
     * </p>
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help. Append ("please enter" + tip + ":");
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
        Throw new mybatisplusexception ("please enter the correct" + tip + "!");

    public static void main(String[] args) {
        //Code generator
        AutoGenerator mpg = new AutoGenerator();

        //Global configuration
        GlobalConfig gc = new GlobalConfig();
//        String projectPath = System.getProperty("user.dir");
        String projectPath = "/Users/shibo_zhong/Documents/workspace-prepared/spring-boot-learning/spring-boot-mybatis-plus";
        gc.setOutputDir(projectPath + "/src/main/java");
        // gc. setSwagger2(true);  Entity attribute swagger2 annotation

        //Data source configuration
        DataSourceConfig dsc = new DataSourceConfig();
        // dsc.setSchemaName("public");

        //Package configuration
        PackageConfig pc = new PackageConfig();
        Pc.setmodulename (scanner ("module name");

        //Custom configuration
        InjectionConfig cfg = new InjectionConfig() {
            public void initMap() {
                // to do nothing

        //If the template engine is freemaker
        String templatePath = "/templates/mapper.xml.ftl";
        //If the template engine is velocity
        // String templatePath = "/templates/mapper.xml.vm";

        //Custom output configuration
        List<FileOutConfig> focList = new ArrayList<>();
        //Custom configuration会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            public String outputFile(TableInfo tableInfo) {
                //Customize the output file name. If you set the Prefix suffix for entity, please note that the name of XML will change accordingly!!
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
        cfg.setFileCreate(new IFileCreate() {
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                //Determine whether custom folders need to be created
                Checkdir ("the directory created by calling the default method is used for custom directories");
                if (fileType == FileType.MAPPER) {
                    //The mapper file has been generated and it is judged that it exists. If you do not want to regenerate it, false is returned
                    return !new File(filePath).exists();
                //Allow template file generation
                return true;

        //Configuration template
        TemplateConfig templateConfig = new TemplateConfig();

        //Configure custom output templates
        //Specify a custom template path. Be careful not to bring it with you ftl/. VM, which will be automatically identified according to the template engine used
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();


        //Policy configuration
        StrategyConfig strategy = new StrategyConfig();
//        strategy. Setsuperentityclass ("your own parent entity, no need to set it!");
        //Public parent
//        strategy. Setsupercontrollerclass ("your own parent controller, no need to set it!");
        //Public fields written in the parent class
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());


Execute the main method and follow the prompts to generate code

Please enter the module name:
Please enter tuser:

The generated code is as follows:

Spring boot integrates mybatis plus

3 verification

Writing test classes

public class MybatisPlusApplicationTests {

    private TuserMapper tuserMapper;

    public void testAddUser() {
        Tuser tuser = new Tuser();

Integration completed!

GitHub open source address

API documentation

This article deals with code addresses

Recommended Today

Modern Enterprise Architecture Framework – Application Architecture

Modern Enterprise Architecture Framework:https://mp.weixin.qq.com/s/SlrEu0_t0slijrNZ6DP4Ng Business Architecture:https://mp.weixin.qq.com/s/zQCjiHuxFvAg5QiOAuLAcQ 4. Application Architecture The core concern of application architecture is which applications carry the business requirements, how they interact with users, how and how they interact, and what data they access or change. The design of the application architecture is mainly based on the application (Application) design as the […]