Automatically generate code: MyBatis Generator and MyBatis-Plus AutoGenerator

Automatic code generation is a very common technology now, which can greatly improve development efficiency and reduce duplication of work. In Java development, MyBatis is a very popular ORM framework, and the Generator and the AutoGenerator in MyBatis-Plus are two very easy-to-use automated code generation tools. Let's introduce their use respectively.

Mybatis Generator automatically generates code

MyBatis Generator Overview

MyBatis Generator is a tool for automatically generating code provided by the MyBatis framework. It can automatically generate corresponding POJOs, Mapper interfaces and XML configuration files based on tables in the database. It also supports the development of custom plug-ins. The steps to use MyBatis Generator are as follows:

Use Java code form

1. Add the dependency of MyBatis Generator in Maven or Gradle:

<dependency>
  <groupId>org.mybatis.generator</groupId>
  <artifactId>mybatis-generator-core</artifactId>
  <version>1.4.0</version>
</dependency>

2. Write the configuration file GeneratorConfig.xml to configure the database tables and corresponding generators that need to be generated:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
    PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
    "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <context id="testTables" targetRuntime="MyBatis3">
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/test"
            userId="root"
            password="root" />

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <javaModelGenerator targetPackage="com.example.pojo"
            targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="com.example.mapper"
            targetProject="src/main/resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <javaClientGenerator type="XMLMAPPER"
            targetPackage="com.example.mapper"
            targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <table tableName="tb_user" domainObjectName="User"
            enableCountByExample="false" enableUpdateByExample="false"
            enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false" />

    </context>
</generatorConfiguration>

3. Use MyBatis Generator on the command line for code generation:

java -jar mybatis-generator-core-1.4.0.jar -configfile GeneratorConfig.xml -overwrite

This will generate the corresponding POJO, Mapper interface and XML configuration files under the specified package path and project path. But writing code also requires configuring some information, which is quite troublesome. Let's be lazy and use the Maven plug-in to help us do the work.

Using Maven plugin

Add dependencies in pom.xml

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

Add plugins under build-plugins in pom.xml

After adding the plug-in, we use the configurationFile element to specify a configuration file mybatis-generator-config.xml
and the database table may change, so we need to append a configuration <overwrite>true</overwrite>to allow the old file to be overwritten. In order to prevent the SQL statements we wrote from being overwritten, MyBatis Generator will only overwrite the old po and dao, but *mapper.xml will not overwrite, but append.

<!-- MyBatis Generator 插件 -->
<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.7</version>
    <configuration>
        <!-- MyBatis Generator 生成器的配置文件-->
        <configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile>
        <!-- 允许覆盖生成的文件,确定骨架代码后就可以设为 false 了,免得覆盖原有代码 -->
        <overwrite>true</overwrite>
        <!-- 将当前 pom 的依赖项添加到生成器的类路径中-->
        <includeCompileDependencies>true</includeCompileDependencies>
    </configuration>
</plugin>

The structure is as follows:
Insert image description here

mybatis-generator-config.xml

<generatorConfiguration>
    <context id="myContext" targetRuntime="MyBatis3" defaultModelType="flat">

        <!-- 注释 -->
        <commentGenerator>
            <!-- 是否不生成注释 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!-- jdbc连接 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Shanghai&amp;useSSL=false"
                        userId="root"
                        password="1234">
        </jdbcConnection>

        <!-- 类型转换 -->
        <javaTypeResolver>
            <!--是否使用bigDecimal,默认false。
                false:把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer
                true:把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal-->
            <property name="forceBigDecimals" value="true"/>
        </javaTypeResolver>

        <!-- 生成实体类地址 -->
        <javaModelGenerator targetPackage="com.example.pojo" targetProject="src/main/java">
            <!-- 是否针对string类型的字段在set方法中进行修剪,默认false -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>


        <!-- 生成Mapper.xml文件 -->
        <sqlMapGenerator targetPackage="com.example.mapper" targetProject="src/main/resources">
        </sqlMapGenerator>

        <!-- 生成 XxxMapper.java 接口-->
        <javaClientGenerator targetPackage="com.example.mapper" targetProject="src/main/java" type="XMLMAPPER">
        <property name="enableSubPackages" value="true" />
        </javaClientGenerator>


        <!-- schema为数据库名,oracle需要配置,mysql不需要配置。
             tableName为对应的数据库表名
             domainObjectName 是要生成的实体类名(可以不指定,默认按帕斯卡命名法将表名转换成类名)
             enableXXXByExample 默认为 true, 为 true 会生成一个对应Example帮助类,帮助你进行条件查询,不想要可以设为false
             -->
        <table schema="" tableName="posts" domainObjectName="Posts"
               enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
               enableUpdateByExample="false" selectByExampleQueryId="false">
        </table>
    </context>
</generatorConfiguration>

run

Insert image description here

MyBatis-Plus 的 AutoGenerator

MyBatis-Plus AutoGenerator Overview

MyBatis-Plus is a framework that extends some functions based on MyBatis. AutoGenerator is a tool for automatically generating code provided by MyBatis-Plus. It can generate corresponding POJOs, Mapper interfaces and XML configuration files with one click, and also supports templates. Engine customization.

The steps to use MyBatis-Plus AutoGenerator are as follows:

1. Add the dependency of MyBatis-Plus in Maven or Gradle:

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

2. Configure the data source and MyBatis-Plus related configuration:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

mybatis-plus:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.pojo
  global-config:
    db-config:
      id-type: auto

3. Write the configuration file MybatisPlusConfig.java to configure the relevant information of automatically generated code:

@Configuration
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean
    public MybatisPlusPropertiesCustomizer plusPropertiesCustomizer() {
        return plusProperties -> plusProperties.getGlobalConfig().setBanner(false);
    }

    @Bean
    public AutoGenerator autoGenerator(DataSource dataSource) {
        AutoGenerator autoGenerator = new AutoGenerator();
        autoGenerator.setDataSource(dataSource);

        // 全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
        globalConfig.setAuthor("mybatis-plus");
        globalConfig.setFileOverride(true);
        globalConfig.setOpen(false);
        globalConfig.setEntityName("%sDO");
        autoGenerator.setGlobalConfig(globalConfig);

        // 数据库表配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setEntityLombokModel(true);
        strategyConfig.setRestControllerStyle(true);
        strategyConfig.setControllerMappingHyphenStyle(true);
        strategyConfig.setInclude("tb_user");

        // 包配置
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent("com.example");
        packageConfig.setEntity("pojo");
        packageConfig.setMapper("mapper");
        packageConfig.setXml("mapper");

        // 模板引擎配置
        TemplateConfig templateConfig = new TemplateConfig();

        // 自定义模板配置,可以根据自己的需求进行修改
        templateConfig.setService("/templates/service.vm");
        templateConfig.setServiceImpl("/templates/serviceImpl.vm");
        templateConfig.setEntity("/templates/entity.vm");
        templateConfig.setMapper("/templates/mapper.vm");
        templateConfig.setXml("/templates/mapperXml.vm");

        autoGenerator.setTemplate(templateConfig);
        autoGenerator.setPackageInfo(packageConfig);
        autoGenerator.setStrategy(strategyConfig);

        return autoGenerator;
    }
}

4. Call the run method of AutoGenerator in the startup class to generate code:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);

        AutoGenerator autoGenerator = (AutoGenerator) ApplicationContextUtils.getBean("autoGenerator");
        autoGenerator.execute();
    }
}

In this way, the corresponding POJO, Mapper interface and XML configuration files can be generated under the specified package path and project path.

Compare the two

Dimensions MyBatis Generator MyBatis-Plus AutoGenerator
Depend on configuration You need to add a separate dependency of MyBatis Generator Need to add the overall dependency of MyBatis-Plus
Configuration file Need to write GeneratorConfig.xml configuration file No additional configuration files required
Support database Support mainstream relational databases (such as MySQL, Oracle, etc.) Support mainstream relational databases (such as MySQL, Oracle, etc.)
Content can be generated POJO, Mapper interface and XML configuration file POJO, Mapper interface and XML configuration file
Plug-in support Support custom plug-in development Supports the use of MyBatis-Plus built-in plug-ins
Template engine support Template engine not supported Supports customization using template engines
Configuration flexibility Many configuration items and high flexibility Fewer configuration items, but easier to use
compatibility Good version compatibility with MyBatis Need to be used with MyBatis-Plus version
Community support and documentation Good community support and rich documentation Community support is good, but the amount of documentation is relatively small

To sum up, MyBatis Generator and MyBatis-Plus AutoGenerator are both very easy-to-use automated code generation tools. Depending on the project needs, we can choose the tool that suits us for development. MyBatis Generator has high configuration flexibility and can develop custom plug-ins as needed, but requires writing more configuration files. MyBatis-Plus AutoGenerator is simpler and supports template engine customization, but has fewer configuration items.

Summarize

The above is the usage and difference of two automated code generation tools, MyBatis Generator and MyBatis-Plus AutoGenerator. They can greatly improve development efficiency and reduce duplication of work. In actual development, we can choose appropriate tools to use according to the needs of the project.

Guess you like

Origin blog.csdn.net/aqiuisme/article/details/132635406
Recommended