SpringBoot automatically generates code in conjunction with MyBatis Plus

This chapter is about Redis+AOP optimization privileges, but I still need to introduce some MyBatis Plus automatic generation code

MyBatis Plus introduction

MyBatis-Plus (Opens New Window) (MP) is a new enhancement tool for MyBatis (Opens New Window), which is designed to simplify development and improve efficiency.

MyBatis Plus features

  • No intrusion: only enhancements are made, no changes are made, and its introduction will not affect the existing project, as smooth as silk
  • Low loss: Basic CURD will be injected automatically upon startup, with basically no loss in performance and direct object-oriented operation
  • Powerful CRUD operations: built-in universal Mapper, universal Service, only through a small amount of configuration can achieve a single table most CRUD operations, more powerful condition constructor, to meet all types of use requirements
  • Support Lambda form call: through Lambda expressions, it is convenient to write all kinds of query conditions, without worrying about field write errors
  • Support automatic generation of primary keys: support up to four primary key policies (including distributed unique ID generator – Sequence), can be freely configured, perfect solution to the primary key problem
  • Support for ActiveRecord mode: Support for ActiveRecord form calls, entity classes only need to inherit from Model classes to perform powerful CRUD operations
  • Support custom global universal operations: support Write once (use anywhere)
  • Built-in code generator: using code or Maven plug-in can quickly generate Mapper, Model, Service, Controller layer code, support template engine, more than a lot of custom configuration you to use
  • Built-in paging plug-in: Based on MyBatis physical paging, developers do not need to care about specific operations, after configuring the plug-in, write paging is equal to ordinary List query
  • The paging plug-in supports a variety of databases: MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer, etc
  • Built-in performance analysis plug-in: outputs Sql statements and their execution time. It is recommended to enable this function during development and testing to quickly find out slow queries
  • Built-in global interception plug-in: provides intelligent analysis and blocking of delete and UPDATE operations on all tables, and can customize interception rules to prevent misoperations

MyBatis Plus supports databases

Any database that can cruD with Mybatis and supports standard SQL

Frame structure


MyBatis Plus code generator

AutoGenerator is the code generator of MyBatis-Plus, through which the code of Entity, Mapper, Mapper XML, Service, Controller and other modules can be generated quickly. Greatly improved the development efficiency.

Using the tutorial

Add code generator dependencies

<! - lombok dependence - >

        <dependency>

            <groupId>org.projectlombok</groupId>

            <artifactId>lombok</artifactId>

            <optional>true</optional>

        </dependency>

<! Druid connection pool -->

        <dependency>

            <groupId>com.alibaba</groupId>

            <artifactId>druid-spring-boot-starter</artifactId>

The < version > 1.1.10 < / version >

        </dependency>

<! Mysql database driver -->

        <dependency>

            <groupId>mysql</groupId>

            <artifactId>mysql-connector-java</artifactId>

The < version > 5.1.10 < / version >

        </dependency>

<! --MyBatis Plus dependencies -->

        <dependency>

            <groupId>com.baomidou</groupId>

            <artifactId>mybatis-plus-boot-starter</artifactId>

The < version > 3.3.2 rainfall distribution on 10-12 < / version >

        </dependency>

<! --MyBatis Plus code generator -->

        <dependency>

            <groupId>com.baomidou</groupId>

            <artifactId>mybatis-plus-generator</artifactId>

The < version > 3.3.2 rainfall distribution on 10-12 < / version >

        </dependency>

<! --Hutool Java Toolkit -->

        <dependency>

            <groupId>cn.hutool</groupId>

            <artifactId>hutool-all</artifactId>

The < version > 4.5.7 < / version >

        </dependency>

<! --Velocity template engine -->

        <dependency>

            <groupId>org.apache.velocity</groupId>

            <artifactId>velocity-engine-core</artifactId>

< version > 2.2 < / version >

        </dependency>

<! --Swagger -- UI API -->

        <dependency>

            <groupId>io.springfox</groupId>

            <artifactId>springfox-swagger2</artifactId>

The < version > 2.7.0 < / version >

        </dependency>

        <dependency>

            <groupId>io.springfox</groupId>

            <artifactId>springfox-swagger-ui</artifactId>

The < version > 2.7.0 < / version >

        </dependency>

Copy the code

Add template engine dependencies

MyBatis-Plus supports Velocity (default), Freemarker, Beetl, and you can choose a template engine you are familiar with. If none of them meet your requirements, you can use a custom template engine. This article uses default dependencies

<dependency>

    <groupId>org.apache.velocity</groupId>

    <artifactId>velocity-engine-core</artifactId>

< version > 2.2 < / version >

</dependency>

Copy the code

Write the configuration

The MyBatis-Plus code generator provides a large number of custom parameters for users to choose from, and can satisfy the needs of most people.

Configuration GlobalConfig

Global policy globalConfig configuration

/ * *

* Global configuration

     * @param projectPath

     * @return

* /

    public static GlobalConfig initGlobal(String projectPath){

        GlobalConfig gc = new GlobalConfig();

        gc.setOutputDir(projectPath + "/src/main/java");

        gc.setAuthor("zbb");

        gc.setOpen(false);

        gc.setSwagger2(true);

        gc.setBaseResultMap(true);

        gc.setFileOverride(true);

        gc.setDateType(DateType.ONLY_DATE);

        gc.setEntityName("%s");

        gc.setMapperName("%sMapper");

        gc.setXmlName("%sMapper");

        gc.setServiceName("%sService");

        gc.setServiceImplName("%sServiceImpl");

        gc.setControllerName("%sController");

        return gc;



    }

Copy the code

Configuration DataSourceConfig

/ * *

     *

* the configuration DataSourceConfig

     * @return

* /

    public  static DataSourceConfig initDataSource() {

        Props props = new Props("application.properties");

        DataSourceConfig dataSourceConfig = new DataSourceConfig();

        dataSourceConfig.setUrl(props.getStr("dataSource.url"));

        dataSourceConfig.setDriverName(props.getStr("dataSource.driverName"));

        dataSourceConfig.setUsername(props.getStr("dataSource.username"));

        dataSourceConfig.setPassword(props.getStr("dataSource.password"));

        return dataSourceConfig;

    }

Copy the code

Package configuration Package name configuration

/ * *

* package configuration

     * @param packname

     * @return

* /

    public  static  PackageConfig initPackage(String packname){

        Props props = new Props("application.properties");

        PackageConfig packageConfig = new PackageConfig();

        packageConfig.setModuleName(packname);

        packageConfig.setParent(props.getStr("package.base"));

        packageConfig.setEntity("model");

        return packageConfig;

    }

Copy the code

The template is configured with TemplateConfig

/ * *

* Template configuration

     * @return

* /

    public static TemplateConfig initTemplate() {

        TemplateConfig templateConfig = new TemplateConfig();

// You can configure the Controller, service, and Entity templates

        templateConfig.setXml(null);

        return templateConfig;

    }



Copy the code

Custom property injection InjectionConfig

map

  • User-defined Returns the configuration Map object
  • The object can be passed to the template engine via cfg.xxx reference

fileOutConfigList

  • Customize the output file
  • Configure FileOutConfig to specify template files and output files to generate customized files

fileCreate

  • Custom determines whether to create a file
  • Implement IFileCreate interface

This configuration is used to determine whether a class needs to be overridden. Of course, you can implement the differential algorithm merge file yourself

initMap

  • Inject a custom Map object (note that setMap is required)
/ * *

* Custom property injection

* /

    public static InjectionConfig initInjection(String projectPath, String moduleName) {

// Custom configuration

        InjectionConfig injectionConfig = new InjectionConfig() {

            @Override

            public void initMap() {

// Can be used to customize attributes

            }

        };

// The template engine is Velocity

        String templatePath = "/templates/mapper.xml.vm";

// Customize the output configuration

        List<FileOutConfig> focList = new ArrayList<>();

// Custom configurations are printed first

        focList.add(new FileOutConfig(templatePath) {

            @Override

            public String outputFile(TableInfo tableInfo) {

// Customize the output file name. If your Entity has a prefix or suffix, note that the XML name will change accordingly!!

                return projectPath + "/src/main/resources/mapper/" + moduleName

                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;

            }

        });

        injectionConfig.setFileOutConfigList(focList);

        return injectionConfig;

    }



Copy the code

Policy configuration StrategyConfig

/ * *

* Policy configuration

* /

    public static StrategyConfig initStrategy(String[] tableNames) {

        StrategyConfig strategyConfig = new StrategyConfig();

        strategyConfig.setNaming(NamingStrategy.underline_to_camel);

        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);

        strategyConfig.setEntityLombokModel(true);

        strategyConfig.setRestControllerStyle(true);

// Wildcard mode can be enabled when the table name contains asterisks

        if (tableNames.length == 1 && tableNames[0].contains("*")) {

            String[] likeStr = tableNames[0].split("_");

            String likePrefix = likeStr[0] + "_";

            strategyConfig.setLikeTable(new LikeTable(likePrefix));

        } else {

            strategyConfig.setInclude(tableNames);

        }

        return strategyConfig;

    }



Copy the code

Code generator

 public static void main(String[] args) {

        String projectPath = System.getProperty("user.dir");

        String moduleName = scanner("Module name");

        String[] tableNames = scanner("Table name, separated by multiple Commas").split(",");

// Code generator

        AutoGenerator autoGenerator = new AutoGenerator();

        autoGenerator.setGlobalConfig(initGlobal(projectPath));

        autoGenerator.setDataSource(initDataSource());

        autoGenerator.setPackageInfo(initPackage(moduleName));

        autoGenerator.setCfg(initInjection(projectPath, moduleName));

        autoGenerator.setTemplate(initTemplate());

        autoGenerator.setStrategy(initStrategy(tableNames));

        autoGenerator.setTemplateEngine(new VelocityTemplateEngine());

        autoGenerator.execute();

    }

Copy the code

Reading console contents

/ * *

     * <p>

* Read the 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 (StrUtil.isNotEmpty(ipt)) {

                return ipt;

            }

        }

        throw new MybatisPlusException("Please enter the correct one" + tip + "!");

    }



Copy the code

Configure the application. The properties

dataSource.url=jdbc:mysql://db:3306/mymes? useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai

dataSource.driverName=com.mysql.jdbc.Driver

dataSource.username=reader

dataSource.password=123456

package.base=com.springboot.mymes_demo.modules

Copy the code

Run the code


Note:

Enter xx_* to indicate all tables with xx prefix. If the full name is entered, the correct table will be generated

No. The public https://mp.weixin.qq.com/s/nfat2WWWUXdmfUGFBAVEuA