To get started quickly, scroll right to the end to see the overall configuration.

MyBatis Generator is a code generation tool provided by MyBatis. It can help us generate persistent objects (Po) for tables, interfaces to manipulate databases (DAO), XML for CRUD SQL (Mapper).

MyBatis Generator is a standalone tool that you can download as a JAR package to run, as well as run in Ant and Maven.

Using the environment

I configured and used it in Maven. This article is also based on the Maven environment.

Since you are using MyBatis Generator, your project must be using MyBatis and must be using some kind of database, and these dependencies should already be configured in Maven.

For example,

Next you need to introduce the MyBatis Generator plug-in into the POM

Introduce the MyBatis Generator plug-in

Add the following configuration under the root of the POM

<build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.7</version> </plugin> </build>Copy the code

Configure the MyBatis Generator plug-in

The MyBatis Generator plugin must be configured as well

Configure the MyBatis Generator Config file path

The MyBatis Generator plugin needs to be run from a MyBatis Generator config file

The configuration is as follows. I used the latest version 1.3.7

<build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> < artifactId > mybatis generator - maven plugin - < / artifactId > < version > 1.3.7 < / version > < configuration > <! - mybatis code generator configuration file - > < configurationFile > SRC/main/resources/mybatis generator - config. XML < / configurationFile > </configuration> </plugin> <plugins> </build>Copy the code

Note that this path is the path of your configuration file relative to the POM file

As for how to configure this file, we will be in later

Allows the generated file to be overwritten

Sometimes we add new fields to our database tables and need to regenerate the corresponding files. The general practice is to manually delete the old file and then generate the new file using MyBatis Generator. Alternatively, you can have MyBatis Generator overwrite old files to avoid manual deletion.

Configuration is as follows

<build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> < artifactId > mybatis generator - maven plugin - < / artifactId > < version > 1.3.7 < / version > < configuration > <! - mybatis code generator configuration file - > < configurationFile > SRC/main/resources/mybatis generator - config. XML < / configurationFile > <! Allow the generated file to be overwritten --> <overwrite>true</overwrite>
            </configuration>
        </plugin>
    <plugins>    
</build>
Copy the code

Note that MyBatis Generator only overwrites old pos and DAOs, while mapper. XML does not overwrite, but appends, the purpose of this is to prevent users from writing their own SQL statements accidentally overwritten by MyBatis Generator

Add database driver dependencies

MyBatis Generator needs to link to a database, so it must have a dependency for the database driver.

Add database driver dependencies to MyBatis Generator as follows

<build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> < artifactId > mybatis generator - maven plugin - < / artifactId > < version > 1.3.7 < / version > < configuration > <! - mybatis code generator configuration file - > < configurationFile > SRC/main/resources/mybatis generator - config. XML < / configurationFile > <! Allow the generated file to be overwritten --> <overwrite>true</overwrite> </configuration> <dependencies> <! <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency> </dependencies> </plugin> </build>Copy the code

The database I use is mysql, and the same goes for any other database. Note the version number of the database driver, the MyBatis Generator configuration is slightly different for each version, which will be covered later.

In most cases, our project has already configured the JDBC driver for the corresponding database, as shown below

Now in the plug-in configuration again, feeling a little redundancy, maven provides includeCompileDependencies properties, let’s reliance on reference in the plug-in dependencies, so you don’t need to repeat the configuration.

Configuration is as follows

<build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> < artifactId > mybatis generator - maven plugin - < / artifactId > < version > 1.3.7 < / version > < configuration > <! - mybatis code generator configuration file - > < configurationFile > SRC/main/resources/mybatis generator - config. XML < / configurationFile > <! Allow the generated file to be overwritten --> <overwrite>true</overwrite> <! - add the current pom dependencies to the generator's classpath - > < includeCompileDependencies >true</includeCompileDependencies>
            </configuration>
        </plugin>
    <plugins>    
</build>
Copy the code

Adding additional dependencies

After the general configuration includeCompileDependencies don’t need to configure other dependence, Because includeCompileDependencies current pom in dependencies will be the Compile phase dependence on all added to the classpath of the generator.

But some people don’t want to configure includeCompileDependencies, or want to MyBatis Generator using another version of the dependency in the plug-in, you can configure dependencies

As shown in figure

In addition, MOST articles on the Internet will configure the mybatis-generator-core dependency, but there is no case on the Mybatis Generator website to configure this dependency. I did not configure this dependency, and mybatis Generator can be used normally

Configure MyBatis Generator Config

When the MyBatis Generator plug-in is started, it will find the configuration file based on the path you have configured in the POM.

This configuration file is the detail that configures the MyBatis Generator to generate the code.

One of the most important is context, and your configuration file should contain at least one context

Import external configuration files

MyBatis Generator Config can import external configuration files as follows, the path is relative to the current configuration file path

The code is as follows, note that it is configured under

<! --> <properties resource="application-dev.properties"/>
Copy the code

The content of the configuration file is as follows

Configure the context

Note that the configuration is under

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

</context>
Copy the code
  • Id: Fill in any context ID. Ensure that multiple context ids do not duplicate
  • DefaultModelType: optional, default conditional, flat indicates that a table corresponds to a Po
  • TargetRuntime: optional. The default value is MyBatis3. MyBatis3Simple is also commonly used

TargetRuntime = MyBatis3, the dao and mapper.xml are generated as follows

TargetRuntime = MyBatis3Simple, generate dao and mapper.xml as follows, the interface will be much less, only the most commonly used

The context is done. The only thing you need to be aware of is the value of targetRuntime

Children of context

In the previous section, we just configured the context node. The context has child elements that need to be configured.

The child elements of the context must be configured in the following order. (Yes, that’s right MyBatis Generator has requirements for sequential configuration)

  1. property (0.. N)
  2. plugin (0.. N)
  3. commentGenerator (0 or 1)
  4. JdbcConnection (connectionFactory or jdbcConnection required)
  5. javaTypeResolver (0 or 1)
  6. JavaModelGenerator (at least 1)
  7. sqlMapGenerator (0 or 1)
  8. javaClientGenerator (0 or 1)
  9. table (1.. N)

plugin

Configure a plug-in, for example

<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
Copy the code

This plug-in adds equals and hashCode methods to the generated Java model objects

commentGenerator

The commentGenerator is used to configure the generated comments. Comments are generated by default and a timestamp is generated, as shown below

commentGenerator

If you do not want to keep the timestamp, the following configuration is required

<commentGenerator> <! -- Do not want generated comments to contain timestamps --> <property name="suppressDate" value="true"/>
</commentGenerator>
Copy the code

If you want to know the meaning of each field in the database (if you have added a comment to the corresponding field in the database), you can do the following configuration

<commentGenerator> <! -- Add comment to db table --> <property name="addRemarkComments" value="true"/>
</commentGenerator>
Copy the code

To be honest, MyBatis Generator generates too many useless comments, so I generally choose not to generate them

<commentGenerator> <! <property name="suppressAllComments" value="true"/>
</commentGenerator>
Copy the code

jdbcConnection

MyBatis Generator needs to connect to a database, so you need to configure jdbcConnection as follows

<jdbcConnection driverClass="${spring.datasource.driverClassName}"
                connectionURL="${spring.datasource.url}"
                userId="${spring.datasource.username}"
                password="${spring.datasource.password}"> <! NullCatalogMeansCurrent = is required for higher versions of mysql-connector-Javatrue-->
    <property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
Copy the code

${} inside is the “name” in the external configuration file.

You can also write to death without having to configure

The corresponding database will not be found, according to the official website

For specific reasons refer to this article MyBatis Generator trampling and Self-rescue

javaTypeResolver

JavaTypeResolver is used to configure JDBC to Java type conversion rules, or you can use its default conversion rules without configuration.

Even if configured, only conversions of bigDecimal and time types can be configured

<javaTypeResolver> <! -- Whether to use bigDecimal, defaultfalse.false, resolve the JDBC DECIMAL and NUMERIC types to Integertrue, parse JDBC DECIMAL and NUMERIC types to java.math.bigDecimal --> <property name="forceBigDecimals" value="true"/ > <! - the defaultfalse
        false, resolve all JDBC time types to java.util.datetrue. DATE -> java.time.LocalDate time -> java.time.LocalTime TIMESTAMP -> java.time.LocalDateTime TIME_WITH_TIMEZONE -> java.time.OffsetTime TIMESTAMP_WITH_TIMEZONE -> java.time.OffsetDateTime --> <property name="useJSR310Types" value="true"/>
</javaTypeResolver>
Copy the code

javaModelGenerator

Configure the package path and project path generated by the Po as follows

<javaModelGenerator targetPackage="com.wqlm.boot.user.po" targetProject="src/main/java"> <! -- Whether to use schema as the suffix for the package, default isfalse-- > <! --<property name="enableSubPackages" value="false"/ > -- > <! -- Specifies whether a field of type string is usedsetMethod for pruning, defaultfalse -->
    <property name="trimStrings" value="true"/>
</javaModelGenerator>
Copy the code

The generated set method looks like this

It is possible to create a “database name” folder in the Po directory. The generated Po will be placed in this folder

sqlMapGenerator

Configure the generation directory for the mapper. XML file

<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"> <! --<property name="enableSubPackages" value="false"/>-->
</sqlMapGenerator>
Copy the code

javaClientGenerator

Configure the xxxmapper. Java file generation directory

<javaClientGenerator targetPackage="com.wqlm.boot.user.dao" targetProject="src/main/java" type="XMLMAPPER"> <! --<property name="enableSubPackages" value="false"/>-->
</javaClientGenerator>
Copy the code

Type =”XMLMAPPER” places the implementation of the interface in mapper.xml, which is also recommended. You can also set type to another value, such as type=”ANNOTATEDMAPPER”, and the implementation of the interface is annotated on the interface, as shown in the figure

If you do this, mapper.xml will not be generated and

will not be configured, but it is fine to use annotations to implement the interface for simple queries. For complex queries that are not as convenient as XML, it is recommended that type be configured as XMLMAPPER

table

One table corresponds to one table. To generate multiple tables at the same time, you need to configure multiple tables

<! -- Schema indicates the name of the database. Oracle needs to be configured, but mysql does not. TableName is the name of the corresponding database table. DomainObjectName is the name of the entity class to be generated.enableXXXByExample defaults totruefortrueAn Example helper class will be generated to help you with the query. If you don't want it, set it tofalse
     -->
<table schema="" tableName="user" domainObjectName="User"
       enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
       enableUpdateByExample="false" selectByExampleQueryId="false"> <! -- Whether to use the actual column namefalse-- > <! --<property name="useActualColumnNames" value="false" />-->
</table>
Copy the code

If domainObjectName is not configured, it converts the table name to the class name according to PASCAL naming

EnableXXXByExample defaults to true, but only works if targetRuntime=”MyBatis3″

When it takes effect, an additional xxxexample.java file will be generated under Po as follows

EnableXXXByExample is not true or false when targetRuntime=”MyBatis3Simple”

The overall configuration

Pom configuration

<build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> < artifactId > mybatis generator - maven plugin - < / artifactId > < version > 1.3.7 < / version > < configuration > <! - mybatis code generator configuration file - > < configurationFile > SRC/main/resources/mybatis generator - config. XML < / configurationFile > <! Allow the generated file to be overwritten --> <overwrite>true</overwrite> <! Add the current POM dependencies to the generator's classpath --> <! --<includeCompileDependencies>true</includeCompileDependencies>--> </configuration> <dependencies> <! -- Mybatis -Generator plugin dependencies --> <! --<dependency>--> <! --<groupId>org.mybatis.generator</groupId>--> <! --<artifactId>mybatis-generator-core</artifactId>--> <! - < version > 1.3.7 < / version > -- > <! --</dependency>--> <! <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency> </dependencies> </plugin> </plugins> <build>Copy the code

MyBatis Generator Config overall configuration

<? xml version="1.0" encoding="UTF-8"? > <! Mybatis code generator configuration --> <! DOCTYPE generatorConfiguration PUBLIC"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <! --> <properties resource="application-dev.properties"/ > <! A database has a context, and the children of the context must be in the order they are given. Property *,plugin*,commentGenerator? ,jdbcConnection,javaTypeResolver? , javaModelGenerator,sqlMapGenerator? ,javaClientGenerator? ,table+ --> <context id="myContext" targetRuntime="MyBatis3" defaultModelType="flat"> <! -- This plugin adds equals and equals to the generated Java model objectshashCode method --> <! --<plugintype="org.mybatis.generator.plugins.EqualsHashCodePlugin"/ > -- > <! -- Comments --> <commentGenerator> <! <property name="suppressAllComments" value="true"/ > <! -- Do not want generated comments to contain timestamps --> <! --<property name="suppressDate" value="true"/ > -- > <! Add comments for fields in DB table, only suppressAllCommentsfalseWhen --> <! --<property name="addRemarkComments" value="true"/>--> </commentGenerator> <! -- JDBC connection --> <jdbcConnection driverClass="${spring.datasource.driverClassName}"
                        connectionURL="${spring.datasource.url}"
                        userId="${spring.datasource.username}"
                        password="${spring.datasource.password}"> <! NullCatalogMeansCurrent = is required for higher versions of mysql-connector-Javatrue-->
            <property name="nullCatalogMeansCurrent" value="true"/> </jdbcConnection> <! --> <javaTypeResolver> <! -- Whether to use bigDecimal, defaultfalse.false, resolve the JDBC DECIMAL and NUMERIC types to Integertrue, parse JDBC DECIMAL and NUMERIC types to java.math.bigDecimal --> <property name="forceBigDecimals" value="true"/ > <! - the defaultfalse
                false, resolve all JDBC time types to java.util.datetrue. DATE -> java.time.LocalDate time -> java.time.LocalTime TIMESTAMP -> java.time.LocalDateTime TIME_WITH_TIMEZONE -> java.time.OffsetTime TIMESTAMP_WITH_TIMEZONE -> java.time.OffsetDateTime --> <! --<property name="useJSR310Types" value="false"/>--> </javaTypeResolver> <! Generate entity class address --> <javaModelGenerator targetPackage="com.wqlm.boot.user.po" targetProject="src/main/java"> <! -- Whether to use schema as the suffix for the package, default isfalse-- > <! --<property name="enableSubPackages" value="false"/ > -- > <! -- Specifies whether a field of type string is usedsetMethod for pruning, defaultfalse -->
            <property name="trimStrings" value="true"/> </javaModelGenerator> <! <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"> <! --<property name="enableSubPackages" value="false"/>--> </sqlMapGenerator> <! Java --> <javaClientGenerator targetPackage="com.wqlm.boot.user.dao" targetProject="src/main/java" type="XMLMAPPER"> <! --<property name="enableSubPackages" value="false"/>--> </javaClientGenerator> <! -- Schema indicates the name of the database. Oracle needs to be configured, but mysql does not. TableName is the name of the corresponding database table. DomainObjectName is the name of the entity class to be generated.enableXXXByExample defaults totruefortrueAn Example helper class will be generated to help you with the query. If you don't want it, set it tofalse
             -->
        <table schema="" tableName="user" domainObjectName="User"
               enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
               enableUpdateByExample="false" selectByExampleQueryId="false"> <! -- Whether to use the actual column namefalse-- > <! --<property name="useActualColumnNames" value="false" />-->
        </table>
    </context>
</generatorConfiguration>
Copy the code

External configuration file configuration as a whole

The external configuration file referenced by MyBatis Generator Config is as follows

# mysqlspring.datasource.driverClassName=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/boot? useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
Copy the code

Use MyBatis Generator

Once configured, double-click MyBatis Generator in Maven to run it

reference

MyBatis Generator’s official website