Mybatis Generator Mybatis Generator is a plug-in for Mybatis (MBG for short). This plug-in can automatically generate entiRY, DAO, and Mapper for you according to the table structure of the data table. Omit the process of writing repeated code, improve the efficiency of programmer development.

1. Integrate MBG plug-in

1.1 Introducing the MBG plug-in

First, you need to introduce the MBG plug-in into Maven’s POM file, as shown below:

<build>
    <plugins>
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.6</version>
            <configuration>
                <! -- Specify MBG configuration file location -->
                <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
                <! Allow generated files with the same name to be overwritten -->
                <overwrite>true</overwrite>
                <! Allows you to display the specific process of file generation.
                <verbose>true</verbose>
            </configuration>
        </plugin>
    <plugins>    
</build>
Copy the code

The MBG plug-in relies on the GeneratorConfig. XML configuration file to run. Therefore, you need to specify the location of the GeneratorConfig. XML configuration file when importing the plug-in.

1.2 Adding Database Dependencies

MBG needs to connect to the database to obtain the table structure information of the data table, so the MBG plug-in needs to rely on the database-related drivers.

<build>
    <plugins>
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.6</version>
            <configuration>
                <! -- Specify MBG configuration file location -->
                <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
                <! Allow generated files with the same name to be overwritten -->
                <overwrite>true</overwrite>
                <! Allows you to display the specific process of file generation.
                <verbose>true</verbose>
            </configuration>
            <dependencies>
                <! -- Database connection driver -->
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>8.0.16</version>
                </dependency>
                <! Add lombok plugin to MBG -->
                <dependency>
                    <groupId>com.softwareloop</groupId>
                    <artifactId>mybatis-generator-lombok-plugin</artifactId>
                    <version>1.0</version>
                </dependency>
            </dependencies>
        </plugin>
    <plugins>    
</build>
Copy the code

GeneratorConfig configuration file

The generatorConfig. XML configuration file controls the set of rules that MBG plug-ins automatically generate code for and where the generated Entity, DAO, and Mapper are stored.

2.1 root tag

The

tag is the root tag of the GeneratorConfig. XML configuration file, and all configuration content is contained under the

tag.

Example:


      
<! DOCTYPEgeneratorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <! -- Specific configuration content -->
</generatorConfiguration>
Copy the code

2.2 the properties TAB

The tag is used to import SpringBoot configuration files. After importing external configuration files, you can reference the required configuration items in the current GeneratorConfig.xml configuration file with ${configuration items}.

Example:


      
<! DOCTYPEgeneratorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <! -- Import external configuration -->
    <properties>application.properties</properties>
    <! -- Specific configuration content -->
</generatorConfiguration>
Copy the code

2.3 the context label

The generatorConfig. XML configuration file has at least one

tag. The connection configuration for the database, automatic generation policy for code, and so on need to be placed under the

tag.

The

tag has three attributes:

  • Id: unique identifier of the context. You can enter this parameter as long as multiple contexts are not duplicated
  • TargetRuntime: code generator, defaultMyBatis3And often usedMyBatis3SimpleThis configuration affects dao and mapper.xml generation
  • DefaultModelType: Controls the generation strategy for database action objects. The default isconditional, optional values:
    • Hierarchical: Generates a primary key entity class for a separate primary key if the table has primary keysBLOBType, and a separate one containing allBLOBThe rest of the normal fields will be in the same entity class.
    • Conditional:hierarchicalSimilar, except that if the table has only 1 primary key, thenconditionalInstead of generating an entity class for this primary key, it is merged into a normal field entity class.
    • Flat: Put all the fields of a data table into one entity class, that is, one data table corresponds to one entity class.

Example:


      
<! DOCTYPEgeneratorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <! -- Import external configuration -->
    <properties>application.properties</properties>
    
    <context id="default" defaultModelType="flat" targetRuntime="MyBatis3">
    </context>
</generatorConfiguration>
Copy the code


allows multiple child tags to define related attributes. Common attributes are as follows:

  • AutoDelimitKeywords: Whether to use delimiters to enclose database keywords (for example, backquotes used in mysql). The default value isfalse
  • BeginningDelimiter: start of the delimiter. The default value is beginningDelimiter""
  • EndingDelimiter: End of the delimiter, default""
  • JavaFileEncoding: File encoding format

Example:


      
<! DOCTYPEgeneratorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <! -- Import external configuration -->
    <properties>application.properties</properties>
    
    <context id="default" defaultModelType="flat" targetRuntime="MyBatis3">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <property name="javaFileEncoding" value="UTF-8"/>
    </context>
</generatorConfiguration>
Copy the code

2.4 commentGenerator label

The

tag controls whether or not comments are generated in the generated entity class. In general, we prevent comments from being generated so that the generated entity class is very clean and concise.

The

tag allows the inclusion of multiple child tags to control the generation of comments, with common properties like the following:

  • SuppressAllComments: Whether to block the generation of all comments. Generally set totrue
  • SuppressDate: Indicates whether to prevent comments from including timetrue
  • DateFormat: Used in conjunction with suppressDate, refers to the fixed date and time format output in the annotation
  • AddRemarkComments: Whether to output comment information about data tables and columns

Example:


      
<! DOCTYPEgeneratorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <! -- Import external configuration -->
    <properties>application.properties</properties>
    
    <context id="default" defaultModelType="flat" targetRuntime="MyBatis3">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <property name="javaFileEncoding" value="UTF-8"/>
        
        <! -- Block comment generation -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>
    </context>
</generatorConfiguration>
Copy the code

2.5 javaTypeResolver label










The mapping of BigDecimal to time and date types can also only be configured using the fourceBigDecimals and useJSR310Types attributes.








  • FourceBigDecimals: The default is false. If false, JDBC BIGDECIMAL and NUMERIC types are mapped to Java Ingeter types; If true, the JDBC BIGDECIMAL and NUMERIC types are mapped to the Java java.math.bigDecimal type

  • UseJSR310Types: Default is false, if false, all JDBC Date and time types are mapped to Java’s java.util.date type; If true, the mapping is as follows:

    The JDBC type Java type
    DATE java.time.LocalDate
    TIME java.time.LocalTime
    TIMESTAMP java.time.LocalDateTime
    TIME_WITH_TIMEZONE java.time.OffsetTime
    TIMESTAMP_WITH_TIMEZONE java.time.OffsetDateTime

Example:


      
<! DOCTYPEgeneratorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <! -- Import external configuration -->
    <properties>application.properties</properties>
    
    <context id="default" defaultModelType="flat" targetRuntime="MyBatis3">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <property name="javaFileEncoding" value="UTF-8"/>
        
        <! -- Block comment generation -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>
        
        <! -- Type mapping -->
        <javaTypeResolver>
            <property name="fourceBigDecimals" value="true"/>
            <property name="useJSR310Types" value="true"/>
        </javaTypeResolver>
    </context>
</generatorConfiguration>
Copy the code

2.6 jdbcConnection label

The

tag is used to configure database connection information and contains the following properties:

  • DriverClass: Specifies the connection driver for the database
  • ConnectionURL: database connectionURL
  • UserId: indicates the user name
  • Password: password

Example:

(1) Application. Properties External configuration

spring.datasource.dirverClassName=com.mysql.jdbc.Driver
spring.datasource.url=JDBC: mysql: / / 127.0.0.1:3306 / example? useSSL=false&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=admin
spring.datasource.password=admin
Copy the code

(2) generatorConfig. XML configuration


      
<! DOCTYPEgeneratorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <! -- Import external configuration -->
    <properties>application.properties</properties>
    
    <context id="default" defaultModelType="flat" targetRuntime="MyBatis3">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <property name="javaFileEncoding" value="UTF-8"/>
        
        <! -- Block comment generation -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>
        
        <! -- Database connection configuration -->
        <jdbcConnection dirverClass="${spring.datasource.driverClassName}"
                        connectionURL="${spring.datasource.url}"
                        userId="${spring.datasource.username}"
                        password="${spring.datasource.password}">
            <! NullCatalogMeansCurrent = true; nullCatalogMeansCurrent = true;
            <property name="nullCatalogMeansCurrent" value="true"/>
        </jdbcConnection>
    </context>
</generatorConfiguration>
Copy the code

2.7 javaModelGenerator label

The

tag is used to configure the code generation behavior of the entity class. The

tag has two attributes, targetPackage and targetProject, as shown below:

  • TargetPackage: Specifies the package name of the entity class
  • TargetProject: Used to specify the location of the entity class (equivalent to the project root directory)

The

tag allows multiple child tags to control the generation strategy of the entity class code. Common attributes are as follows:

  • ConstructorBased: Whether to generate a constructor in the entity class that will contain all fields. Default isfalse, we generally do not need such a constructor
  • EnableSubPackages: Whether subpackages are allowed. The default value is enableSubPackagesfalse
  • Immutable: Whether the field attributes of an entity class are immutable. The default isfalseIf fortrue, no Setter methods are generated in the entity class, and all fields are decorated with the final keyword
  • TrimStrings: Whether a trim() operation is performed on the field in the Setter methodfalse

Example:


      
<! DOCTYPEgeneratorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <! -- Import external configuration -->
    <properties>application.properties</properties>
    
    <context id="default" defaultModelType="flat" targetRuntime="MyBatis3">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <property name="javaFileEncoding" value="UTF-8"/>
        
        <! -- Block comment generation -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>
        
        <! -- Database connection configuration -->
        <jdbcConnection dirverClass="${spring.datasource.driverClassName}"
                        connectionURL="${spring.datasource.url}"
                        userId="${spring.datasource.username}"
                        password="${spring.datasource.password}">
        </jdbcConnection>
        
        <! -- Entity class auto-generate configuration -->
        <javaModelGenerator targetPackage="com.example.entity" targetProject="src/main/java">
            <property name="constructorBased" value="false"/>
            <property name="enableSubPackages" value="true"/>
            <property name="immutable" value="false"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
    </context>
</generatorConfiguration>
Copy the code

2.8 sqlMapGenerator label

The

tag is used to configure the automatic generation behavior of mapper. XML files. The

tag also has two attributes, targetPackage and targetProject, as shown below:

  • TargetPackage: Specifies the package name of the mapper
  • TargetProject: Used to specify the location of mapper files (equivalent to the project root directory)

The

tag also allows a child tag. Commonly used attributes are as follows:

  • EnableSubPackages: Whether subpackages are allowed. The default value is enableSubPackagesfalse

Example:


      
<! DOCTYPEgeneratorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <! -- Import external configuration -->
    <properties>application.properties</properties>
    
    <context id="default" defaultModelType="flat" targetRuntime="MyBatis3">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <property name="javaFileEncoding" value="UTF-8"/>
        
        <! -- Block comment generation -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>
        
        <! -- Database connection configuration -->
        <jdbcConnection dirverClass="${spring.datasource.driverClassName}"
                        connectionURL="${spring.datasource.url}"
                        userId="${spring.datasource.username}"
                        password="${spring.datasource.password}">
        </jdbcConnection>
        
        <! -- Entity class auto-generate configuration -->
        <javaModelGenerator targetPackage="com.example.entity" targetProject="src/main/java">
            <property name="constructorBased" value="false"/>
            <property name="enableSubPackages" value="true"/>
            <property name="immutable" value="false"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        
        <! Mapper.xml file automatic generation configuration -->
        <sqlMapGenerator targetPackage="com.example.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
    </context>
</generatorConfiguration>
Copy the code

2.9 javaClientGenerator label

The

tag is used to configure the automatic generation behavior of the DAO layer interface. The

tag has three properties: Type, targetPackage, and TargetProject. as shown below:

  • Type: indicates the generation policy of the DAO layer interface. Possible values are as follows:
    • ANNOTATIONMAPPER: The DAO layer interface is annotated in a purely annotated manner, relying entirely on annotations and annotations for code generationSqlProvidersIt doesn’t form.xmlfile
    • XMLMAPPER: The DAO layer interface must have a correspondingxmlFile generation, that is, adoptionxmlThe way of
    • MIXEDMAPPER: The DAO layer interface is annotated for simple implementations and annotated for complex implementationsxmlThe way of
  • TargetPackage: Specifies the package name of the mapper
  • TargetProject: Used to specify the location of mapper files (equivalent to the project root directory)

The

tag also allows a child tag. The usual attributes are as follows:

  • EnableSubPackages: Whether subpackages are allowed. The default value is enableSubPackagesfalse

Example:


      
<! DOCTYPEgeneratorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <! -- Import external configuration -->
    <properties>application.properties</properties>
    
    <context id="default" defaultModelType="flat" targetRuntime="MyBatis3">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <property name="javaFileEncoding" value="UTF-8"/>
        
        <! -- Block comment generation -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>
        
        <! -- Database connection configuration -->
        <jdbcConnection dirverClass="${spring.datasource.driverClassName}"
                        connectionURL="${spring.datasource.url}"
                        userId="${spring.datasource.username}"
                        password="${spring.datasource.password}">
        </jdbcConnection>
        
        <! -- Entity class auto-generate configuration -->
        <javaModelGenerator targetPackage="com.example.entity" targetProject="src/main/java">
            <property name="constructorBased" value="false"/>
            <property name="enableSubPackages" value="true"/>
            <property name="immutable" value="false"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        
        <! -- Mapper auto-generate configuration -->
        <sqlMapGenerator targetPackage="com.example.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        
        <! -- Dao layer interface automatic configuration -->
        <sqlMapGenerator type="XMLMAPPER" targetPackage="com.example.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
    </context>
</generatorConfiguration>
Copy the code

2.10 the table tag

The

tag is used to configure the data table required by MBG plug-in to automatically generate code. The
tag has many attributes. Here are some common attributes:
  • TableName: Specifies the data table. This property is mandatory and can be set to if the code is automatically generated for all data tables%
  • EnableInsert: Whether it is automatically generated at the DAO interface layerinsert()Method signature, default istrue
  • EnableSelectByPrimaryKey: Whether it is automatically generatedselectByPrimaryKey()Method, the default istrue
  • EnableSelectByExample: Whether to generate it automaticallyselectByExample()Method, the default istrue
  • EnableUpdateByPrimaryKey: Specifies whether it is automatically generatedupdateByPrimaryKey()Method, the default istrue
  • EnableUpdateByExample: Whether to generate it automaticallyupdateByExample()Method, the default istrue
  • EnableDeleteByPrimaryKey: Whether it is automatically generateddeleteByPrimaryKey()Method, which defaults to ‘tru’
  • EnableDeleteByExample: Whether it is generated automaticallydeleteByExample()Method, the default istrue
  • EnableCountByExample: Whether to generate it automaticallycountByExample()Method, the default istrue

The

tag is a child of the

tag is used, the

tag is added to the INSERT statement in xxmapper.xml.

tag and is used to specify the primary key generation rule. When the

The

tag has the following attributes:

  • Column: specifies the primary key column. In general, it isid
  • SqlStatement: Specifies the query statement for the primary key if the value isMySql, use theSELECT LAST_INSERT_ID()Statement to query the primary key
  • Specified type:<selectKey>Of the labelorderProperty if the value ispre,orderAttribute values forBEFORE, if the value ispost,orderAttribute values forAFTER
  • Identity: The current value istrueWhen,selectKeyOf the labelorderProperties forAFTER

Example:


      
<! DOCTYPEgeneratorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <! -- Import external configuration -->
    <properties>application.properties</properties>
    
    <context id="default" defaultModelType="flat" targetRuntime="MyBatis3">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <property name="javaFileEncoding" value="UTF-8"/>
        
        <! -- Block comment generation -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>
        
        <! -- Database connection configuration -->
        <jdbcConnection dirverClass="${spring.datasource.driverClassName}"
                        connectionURL="${spring.datasource.url}"
                        userId="${spring.datasource.username}"
                        password="${spring.datasource.password}">
        </jdbcConnection>
        
        <! -- Entity class auto-generate configuration -->
        <javaModelGenerator targetPackage="com.example.entity" targetProject="src/main/java">
            <property name="constructorBased" value="false"/>
            <property name="enableSubPackages" value="true"/>
            <property name="immutable" value="false"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        
        <! -- Mapper auto-generate configuration -->
        <sqlMapGenerator targetPackage="com.example.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        
        <! -- Dao layer interface automatic configuration -->
        <sqlMapGenerator type="XMLMAPPER" targetPackage="com.example.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        
        <! Select datafile from datafile -->
        <table tableName="%">
            <generatedKey column="id" sqlStatement="MySql" identity="true"/>
        </table>
    </context>
</generatorConfiguration>
Copy the code

At this point, the entire GeneratorConfig.xml configuration file is basically explained.

Reference documentation

  • Mybatis Generator’s official website
  • Mybatis code Generator Mybatis-Generator