How to use Mybatis-Plus to automatically generate code (super detailed annotations)

1 Introduction

MyBatis-Plus (opens new window) (MP for short) is an enhancement tool for MyBatis (opens new window). On the basis of MyBatis, only enhancements are made without changes, and it was born to simplify development and improve efficiency.
insert image description here

characteristic

  • No intrusion: only enhancement and no change, the introduction of it will not affect the existing project, as smooth as silk
  • Low loss: the basic CURD will be automatically injected when it is started, the performance is basically lossless, and the object-oriented operation is directly performed
  • Powerful CRUD operations: Built-in general Mapper and general Service, most of the CRUD operations on a single table can be realized with only a small amount of configuration, and there is a powerful condition constructor to meet various usage needs
  • Support Lambda form call: through Lambda expressions, it is convenient to write various query conditions, no need to worry about field typos
  • Supports automatic primary key generation: supports up to 4 primary key strategies (including a distributed unique ID generator - Sequence), which can be freely configured to perfectly solve the primary key problem
  • Support ActiveRecord mode: support ActiveRecord form call, the entity class only needs to inherit the Model class to perform powerful CRUD operations
  • Support custom global general operations: support global general method injection ( Write once, use anywhere )
  • Built-in code generator: use code or Maven plug-in to quickly generate Mapper, Model, Service, Controller layer code, support template engine, and more custom configurations are waiting for you to use
  • Built-in paging plug-in: Based on MyBatis physical paging, developers don't need to care about specific operations. After configuring the plug-in, writing paging is equivalent to ordinary List query
  • Paging plug-in supports multiple databases: supports MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer and other databases Built-in
    performance analysis plug-in: can output SQL statements and their execution time, it is recommended to enable this function when developing and testing , can quickly find out slow queries
    Built-in global interception plug-in: provide full table delete, update operation intelligent analysis and blocking, you can also customize the interception rules to prevent misoperation

support database

Any database that can use MyBatis for CRUD and supports standard SQL, the specific support is as follows, if not in the list below, check the pagination part of the tutorial PR for your support.

MySQL,Oracle,DB2,H2,HSQL,SQLite,PostgreSQL,SQLServer,Phoenix,Gauss
,ClickHouse,Sybase,OceanBase,Firebird,Cubrid,Goldilocks,csiidb,informix,TDengine,redshift

Dameng Database, Xugu Database, Renmin University Jincang Database, Nanda General (Huaku) Database, Nanda General Database, Shentong Database, Hangao Database, Youxuan Database

2. Code generator

AutoGenerator is the code generator of MyBatis-Plus. Through AutoGenerator, the code of each module such as Entity, Mapper, Mapper XML, Service, and Controller can be quickly generated, which greatly improves the development efficiency.

/**
 * <p>
 * mysql 代码生成器
 * </p>
 */
public class CodeGenerator {
    
    
    /**
     * 运行启动
     */
    public static void main(String[] args) {
    
    
        //获取控制台的数据
        Scanner scanner = new Scanner(System.in);
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        //~~~~~~~~~~~~~~~~~~~~~全局配置~~~~~~~~~~开始~~~~~~~~~
        GlobalConfig gc = new GlobalConfig();
        //System.out.println("请输入文件输出目录的模块或者项目的地址:");
        //String projectPath = scanner.nextLine();
        String projectPath = System.getProperty("user.dir");    //工程根目录
        System.out.println(projectPath);
        gc.setOutputDir(projectPath + "/src/main/java");        //生成文件的输出目录
        gc.setAuthor("tigerhhzz");                              //作者
        gc.setFileOverride(true);				                //是否覆蓋已有文件 默认值:false
        gc.setOpen(false);                                      //是否打开输出目录 默认值:true
        gc.setBaseColumnList(true);				                //开启 baseColumnList 默认false
        gc.setBaseResultMap(true);				                //开启 BaseResultMap 默认false
        //gc.setEntityName("%sEntity");			                //实体命名方式  默认值:null 例如:%sEntity 生成 UserEntity
        gc.setMapperName("%sMapper");			                //mapper 命名方式 默认值:null 例如:%sDao 生成 UserDao
        gc.setXmlName("%sMapper");				                //Mapper xml 命名方式   默认值:null 例如:%sDao 生成 UserDao.xml
        gc.setServiceName("%sService");			                //service 命名方式   默认值:null 例如:%sBusiness 生成 UserBusiness
        gc.setServiceImplName("%sServiceImpl");	                //service impl 命名方式  默认值:null 例如:%sBusinessImpl 生成 UserBusinessImpl
        gc.setControllerName("%sController");	                //controller 命名方式    默认值:null 例如:%sAction 生成 UserAction
        mpg.setGlobalConfig(gc);
        //~~~~~~~~~~~~~~~~~~~~~全局配置~~~~~~~~~~结束~~~~~~~~~

        //~~~~~~~~~~~~~~~~~~~~~数据源配置~~~~~~~~~~开始~~~~~~~~~
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/tigervueblog?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);
        //~~~~~~~~~~~~~~~~~~~~~数据源配置~~~~~~~~~~结束~~~~~~~~~

        //~~~~~~~~~~~~~~~~~~~~~包配置~~~~~~~~~~开始~~~~~~~~~
        PackageConfig pc = new PackageConfig();
        // pc.setModuleName(scanner("模块名"));
        // pc.setParent("com.stu");
        System.out.println("请输入模块名:");
        String name = scanner.nextLine();
        //自定义包配置
        pc.setParent(name);
        pc.setModuleName(null);
        pc.setMapper("mapper");
        pc.setEntity("domain");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setController("controller");
        mpg.setPackageInfo(pc);
        //~~~~~~~~~~~~~~~~~~~~~包配置~~~~~~~~~~结束~~~~~~~~~

        //~~~~~~~~~~~~~~~~~~~~~自定义配置~~~~~~~~~~开始~~~~~~~~~
        InjectionConfig cfg = new InjectionConfig() {
    
    
            @Override
            public void initMap() {
    
    
                // to do nothing
            }
        };
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
    
    
            @Override
            public String outputFile(TableInfo tableInfo) {
    
    
        // 自定义输入文件名称
                return projectPath + "/src/main/resources/mapper/" + /*pc.getModuleName() + "/" +*/
                        tableInfo.getEntityName() + "Mapper" +
                        StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        //~~~~~~~~~~~~~~~~~~~~~自定义配置~~~~~~~~~~结束~~~~~~~~~

        //这里不自动生成xml,改为自定义生成
        mpg.setTemplate(new TemplateConfig().setXml(null));

        //~~~~~~~~~~~~~~~~~~~~~策略配置~~~~~~~~~~开始~~~~~~~~~
        // 策略配置	数据库表配置,通过该配置,可指定需要生成哪些表或者排除哪些表
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);	    //表名生成策略
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
        //	    strategy.setCapitalMode(true);			            // 全局大写命名 ORACLE 注意
        //	    strategy.setTablePrefix("prefix");		            //表前缀
        //	    strategy.setSuperEntityClass("com.stu.domain");	    //自定义继承的Entity类全称,带包名
        //	    strategy.setSuperEntityColumns(new String[] { "test_id", "age" }); 	//自定义实体,公共字段
        strategy.setEntityLombokModel(true);	                    //【实体】是否为lombok模型(默认 false
        strategy.setRestControllerStyle(true);	                    //生成 @RestController 控制器
        //	    strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");	//自定义继承的Controller类全称,带包名
        //      strategy.setInclude(scanner("表名"));		        //需要包含的表名,允许正则表达式(与exclude二选一配置)
        System.out.println("请输入映射的表名(多个表名英文逗号分割):");
        String tables = scanner.nextLine();
        String[] num = tables.split(",");
        strategy.setInclude(num);                                   // 需要生成的表可以多张表
        //	    strategy.setExclude(new String[]{"test"});          // 排除生成的表
        //如果数据库有前缀,生成文件时是否要前缀acl_
        //      strategy.setTablePrefix("bus_");
        //      strategy.setTablePrefix("sys_");
        strategy.setControllerMappingHyphenStyle(true);	    //驼峰转连字符
        strategy.setTablePrefix(pc.getModuleName() + "_");	//是否生成实体时,生成字段注解
        mpg.setStrategy(strategy);
        //~~~~~~~~~~~~~~~~~~~~~策略配置~~~~~~~~~~结束~~~~~~~~~

        //模板引擎配置,使用Freemarker,默认 Velocity 可选模板引擎 Beetl\
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());

        mpg.execute();
    }
}

3. Detailed tutorial

3.1 Two mysql databases:

m_user script:

CREATE TABLE `m_user` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '自动递增id',
  `username` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户名',
  `avatar` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户头像',
  `email` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '邮箱地址',
  `password` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '密码',
  `status` int NOT NULL DEFAULT '0' COMMENT '0代表正常,-1代表被锁定',
  `created` datetime DEFAULT NULL COMMENT '注册时间',
  `last_login` datetime DEFAULT NULL COMMENT '最后登录时间',
  PRIMARY KEY (`id`),
  KEY `UK_USERNAME` (`username`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;

m_blog script:

CREATE TABLE `m_blog` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `user_id` bigint NOT NULL,
  `title` varchar(255) NOT NULL,
  `description` varchar(255) NOT NULL,
  `content` longtext,
  `created` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP,
  `status` tinyint DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;


3.2 Create a springboot project

insert image description here

3.3 Add dependencies

MyBatis-Plus has removed the default dependencies of the code generator and template engine since 3.0.3, and you need to manually add related dependencies:

The complete pom file of the project: (note the version number)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.tigerhhzz</groupId>
    <artifactId>springboot-mybatisplus-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-mybatisplus-demo</name>
    <description>Demo project for Spring Boot MP</description>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!-- 包含spirng Mvc ,tomcat的包包含requestMapping restController 等注解 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <!--mysql数据库 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <!-- druid 连接池 -->
<!--        <dependency>-->
<!--            <groupId>com.alibaba</groupId>-->
<!--            <artifactId>druid</artifactId>-->
<!--            <version>1.2.8</version>-->
<!--        </dependency>-->
        <!-- mybatis版本必须与druid版本兼容,否则无法创建DataSource -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency>

        <!-- 引入freemarker模板引擎供mp生成代码-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <!--mp代码生成器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.0</version>
        </dependency>
        <!-- hutool工具类-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.3</version>
        </dependency>
        <!-- lombok注解-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- 日志打印-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <!-- 单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

3.5 Edit the application.yml file

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

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    #  test-mybatis
    url: jdbc:mysql://127.0.0.1:3306/tigervueblog?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
    username: root
    password: 123456
  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

3.6 Main startup class

package com.mpautocode;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author tigerhhzz
 * @date 2023/4/28 9:16
 */
@Slf4j
@SpringBootApplication
public class springbootmptest {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(springbootmptest.class, args);
        log.info("springbootmptest启动成功~~~~^…^~~~~^…^~~~~~^…^~~~~");
    }
}

4. Run

4.1 Final project structure

insert image description here

4.2 Running the code generator class

insert image description here
Enter the module name:
insert image description here

Please enter the mapped table name (multiple table names separated by English commas):
insert image description here
generated
insert image description here

4.3 Test run controller

Before running the main startup class, check to add the @Mapper annotation to the generated mapper interface.

Write a usercontroller

package com.mpautocode.controller;


import com.mpautocode.domain.MUser;
import com.mpautocode.service.MUserService;
import com.tigerhhzz.springbootmybatisplusdemo.entities.CommonResult;
import com.tigerhhzz.springbootmybatisplusdemo.entities.User;
import com.tigerhhzz.springbootmybatisplusdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

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

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tigerhhzz
 * @since 2023-04-28
 */
@RestController
@RequestMapping("/m-user")
public class MUserController {
    
    

    @Autowired
    MUserService userService;

    /**
     * list(查询所有)
     * @return
     */
    @GetMapping("/list")
    public CommonResult list(){
    
    
        // 查询所有
        List<MUser> list = userService.list();

        return new CommonResult(200,"查询数据成功",list);
    }

}

operation result:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_43025151/article/details/130411026