[Examples] Spring Boot architecture of integrated Mybatis-Plus Detailed

I. Introduction

MyBatis-Plus (abbreviated MP) is a MyBatis enhancement tools, enhanced not only change on the basis of MyBatis, to simplify development, increase efficiency and health.

characteristic

  • Non-invasive: not only enhance the change, it will not have an impact on the introduction of existing projects, such as silky smooth; 
  • Loss: as a basic injection start automatically CURD i.e., substantially no loss of performance, object-oriented direct operation; 
  • Powerful CRUD operations: built-in universal Mapper, Universal Service, only a small amount of configuration to achieve single-table most of the CRUD operations, more powerful conditions constructors, to meet the various needs through;
  • Lambda forms of support calls: The Lambda expressions, easy preparation of various types of query conditions, without having to worry about the wrong field;
  • Automatic generation of primary key support: supports up to four primary key strategies (Distributed contains a unique ID generator - Sequence), freely configurable, perfect to solve the primary key issue; 
  • Support ActiveRecord model: ActiveRecord form of support calls, just like an entity class inherits Model can be a powerful CRUD operations; 
  • Support custom global General Procedure: general procedure supports global injection (Write once, use anywhere);
  • Built-in code generator: the use of code or Maven plugin can quickly generate Mapper, Model, Service, Controller layer code, support template engine, more and more super custom configuration waiting for you to use;
  • Built-in pagination plug-ins: physical page based on MyBatis, developers need not concern specific operations, after configuring this plugin, written paging equivalent to general inquiries List;
  • Pagination plug-in supports multiple databases: support for MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer and other databases;
  • Built-in performance analysis plug-ins: Sql statement can be output as well as its execution time, it is recommended to enable this feature when developing a test that can quickly ferret out slow query;
  • Built-in global blocking plug-ins: Provide a full table delete, update operational intelligence analysis block, also can customize the blocking rules to prevent misuse. 

Second, how to use

1, dependent on the introduction of the project pom.xml

<!--mybatis-plus依赖-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.2.0</version>
</dependency> 复制代码

2, User class

@Data
public class User {
    private Long id;
    private String name;
    private Date CreateDate;
} 复制代码

3, UserMapper class

public interface UserMapper extends BaseMapper<User> {
} 复制代码

4, application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/testdb?characterEncoding=utf8
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver 复制代码

5, app startup class, increase the allocation MapperScan automatic scanning.

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

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

} 复制代码

6, the write unit test classes tested.

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

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelect() {
        System.out.println(("----- selectAll method test ------"));
        List<User> userList = userMapper.selectList(null);
        //数据库目前两条数据,这块验证一下,如果数量一致则通过,就输出数据信息
        Assert.assertEquals(2, userList.size());
        userList.forEach(System.out::println);
    }
} 复制代码

Here Insert Picture Description

Here Insert Picture Description

Third, the use of the code generator

1, increased reliance project pom.xml

<!--代码生成器-->
<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.29</version>
</dependency> 
复制代码

2, code generation tools

package com.example.mybatisplus.service;

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;

// 演示例子,执行 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.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("jobob");
        gc.setOpen(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/testdb?useUnicode=true&useSSL=false&characterEncoding=utf8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setParent("com.example.mybatisplus.mybatis");
        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.ant.common.BaseEntity");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(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();
    }
} 复制代码

3, operation tools, as follows:

Here Insert Picture Description

Here Insert Picture Description

Have you learned it? Is not Mybatis-Plus configuration is very simple, it also has some powerful features, it is recommended to go to the official website to see the detailed documentation to learn about more exciting technical articles can focus on micro-channel public number: java programmer gathering




Guess you like

Origin juejin.im/post/5de9feb2e51d4558242703be