MyBatis Code Generator (super-detailed explanation)

Why use the MyBatis code generator?

The purpose of the MyBatis Generator is to make it easier for us to be lazy, which is more relevant.
Because when we use the MyBatis framework, we need three components:

  1. Entity Class
  2. Mapper interface
  3. Mapper.xml

When MyBatis code generators are not used, we need to create them manually, with a table corresponding to an entity class, a Mapper interface, and a Mapper.xml.
It's OK to create your own tables with a small number of tables. If you have tens or hundreds of tables, it's hard to create one by one.MyBatis also takes this into account.
So the code generator is provided, we only need to write a few configurations to create the above three components for each table, and in the apper interface and apper.xml created, we have helped to automatically generate the add-delete check code for the single table, that is, using the MyBatis code generator, we no longer need to write code for the add-delete check of the single table.

We use the code generator in the following two steps:

  1. Write Code Generator Configuration File
  2. Run Code Generator

1. Write Code Generator Configuration File

Let's start with a detailed explanation of the Code Generator configuration file, then give the entire configuration code.

  1. The first step is to introduce a template for the configuration file, and then configure it in this XML template
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-// MyBatis Generator Configuration 1.0//EN"
  1. There are only three tags under the generatorConfiguration tag, which are described below.

Properrties Label

  1. The properties tag specifies an external property file that needs to be parsed and used in the configuration. After the property file is introduced, you can use the ${property} form of reference in the configuration to reference the property values in the property file.
  2. The properties tag contains two attributes, resource and url, which can only be specified with one of them, and an error will occur if both attributes are present.

    resource: Specify the properties file under classpath.
    url: Specify a specific location on the file system.

classPathEntry tag

This tag can be configured multiple or not, with only one location attribute.The most common use of this tag is to specify a database-driven path through the location property.

<classPathEntry location="E:\mysql-connector-java-5.1.29.jar"/>

context Label

This tag is configured with at least one tag and can be configured with multiple tags.The context tag specifies the environment in which a set of objects is generated.For example:

  1. Specify the database to connect to
  2. Specify the database tables to be processed
  3. Generate Entity Classes
  4. Generate Mapper Interface
  5. Generate Mapper.xml

The context tag properties are as follows:

  1. Required attribute id, the ID attribute is mainly to distinguish multiple context tags, must be unique, and the ID attribute is used when running the code generator.
  2. The targetRuntime property specifies the runtime environment for the generated code and supports the following optional values:
MyBatis3: Default
 MyBatis3Simple: Method related to Example will not be output in this case.

Next let's look at which subtags are included in the context, and we'll just cover the subtags that are commonly used.

commentGenerator tag

This tag is used to configure how annotation information is generated, up to one can be configured.

  1. suppressAllComments: Prevents comments from being generated.
  2. suppressDate: A comment that prevents generation contains a timestamp.
  3. addRemarkComments: Notes whether to add comment information to a database table.

jdbcConnection tag

This tag is used to specify the database information MBG will connect to. This tag is required and can only have one.

  1. driverClass: The fully qualified class name of the JDBC driver accessing the database.
  2. Connection URL: The JDBC connection URL to access the database.
  3. userId: The user ID to access the database.
  4. Password: The password to access the database.


The configuration of this tag specifies how JDBC and Java types are converted, up to one can be configured.

javaModelGenerator tag

This tag controls the generated entity class.This label must be configured with one and at most one.

  1. targetPackage: Generates the package name stored by the entity class.
  2. targetProject: Specifies the target project path, either relative or absolute.

sqlMapGenerator tag

This tag is used to configure the properties of the SQL Mapper Generator (Mapper.xml file), which is optional and can be configured up to one.

  1. targetPackage: The package name where the generated SQL mapping file is stored.
  2. targetProject: Specifies the target project path, either relative or absolute.

javaClientGenerator tag

This tag is used to generate the Mapper interface and is optional, with a maximum of one configured.

  1. targetPackage: Generate the package name that the Mapper interface stores.
  2. targetProject: Specifies the target project path, either relative or absolute.

table tag

This tag is used to configure tables that need to pass through the introspective database, and only tables that have been configured in the table can generate the final code from the other configurations described above, with a minimum of one being configured.
The table tag has a required property, tableName, that specifies the name of the table to be generated and can use SQL wildcards to match multiple tables.For example, to generate all tables, you can configure the following

<table tableName="%"></table>

The complete configuration file code is given below

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-// MyBatis Generator Configuration 1.0//EN"
    <!--<classPathEntry location="E:\mysql-connector-java-5.1.29.jar"/>-->
    <context id="mybatis" targetRuntime="mybatis3simple" defaultModelType="flat">
            <property name="suppressDate" value="true"/>
            <property name="addRemarkComments" value="true"/>
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            <property name="forceBigDecimals" value="false"/>
        <javaModelGenerator targetPackage="test.model"
            <property name="enableSubPackages" value="false"/>
            <property name="trimStrings" value="false"/>
        <sqlMapGenerator targetPackage="text.xml"
            <property name="enableSubPackages" value="false"/>
        <javaClientGenerator type="XMLMAPPER"
        <table tableName="%">
            <generatedKey column="id" sqlStatement="MySql"/>

Now that the configuration is complete, let's start running the Code Generator, which is where you write code in Java to run it.

2. Run Code Generator with Java Code

We need to introduce the following dependencies in pom.xml

  1. Code Generator Core Dependencies
  2. MyBatis Framework Dependency
  3. MySQL Database Driven Dependency

Then write the Java code run code generator configuration file

 *  Read MBG Generation Code
public class MyBatisGenerator {
    public static void main(String[] args) throws Exception {
        //Warning information during MBG execution
        List<String> warnings = new ArrayList<String>();
        //Overwrite the original code when the generated code is duplicated
        boolean overwrite = true;
        //Read our MBG profile
        InputStream is = MyBatisGenerator.class.getResourceAsStream("/generator/mbg-config.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(is);

        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        //Create MBG
        org.mybatis.generator.api.MyBatisGenerator myBatisGenerator = new org.mybatis.generator.api.MyBatisGenerator(config, callback, warnings);
        //Execute Generated Code
        //Output warning information
        for(String warning : warnings){

The results after running are as follows. For the tables we specified, MBG generates all the corresponding entity classes, Mapper interfaces, and Mapper.xml for us, which is super convenient.

The source code for this code generator and the sql representation statements are available at the following links
Code Generator Source

33 original articles were published, 11 were praised, 10,000 visits+
Private letter follow

Tags: Mybatis xml Database Java

Posted on Sun, 08 Mar 2020 22:30:52 -0400 by bznutz