Spring boot integrates mybatis plus

Time:2022-6-22

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

<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-boot-starter</artifactId>
  <version>3.2.0</version>
</dependency>

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.17</version>
</dependency>

PS: you can modify the version by yourself.

2.2 configuration database YML

spring:
  datasource:
    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
logging:
  level:
    com.baomidou.mybatisplus.samples: debug

2.3 add config file

@Configuration
@MapperScan("com.prepared.mapper")
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
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
    return interceptor;
}

2.4 integrated code generator

Import POM package

<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-generator</artifactId>
  <version>3.4.1</version>
</dependency>
<dependency>
  <groupId>org.freemarker</groupId>
  <artifactId>freemarker</artifactId>
  <version>2.3.28</version>
</dependency>

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 + ":");
        System.out.println(help.toString());
        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.setAuthor("prepared");
        gc.setOpen(true);
        // gc. setSwagger2(true);  Entity attribute swagger2 annotation
        mpg.setGlobalConfig(gc);

        //Data source configuration
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);

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

        //Custom configuration
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            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) {
            @Override
            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() {
            @Override
            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;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        //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();

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

        //Policy configuration
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//        strategy. Setsuperentityclass ("your own parent entity, no need to set it!");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        //Public parent
//        strategy. Setsupercontrollerclass ("your own parent controller, no need to set it!");
        //Public fields written in the parent class
        strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("tuser").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}

Execute the main method and follow the prompts to generate code

Please enter the module name:
prepared
Please enter tuser:
tuser

The generated code is as follows:

Spring boot integrates mybatis plus

3 verification

Writing test classes

@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisPlusApplicationTests {

    @Resource
    private TuserMapper tuserMapper;

    @Test
    public void testAddUser() {
        Tuser tuser = new Tuser();
        tuser.setAge(1);
        tuser.setIdCard("123415413");
        tuser.setIsmale(Boolean.TRUE);
        tuser.setName("prepared");
        tuserMapper.insert(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 […]