Mybatis generator code automatic generator, free your hands from now on

Time:2022-5-6

preface

In our daily development work, we often need to build the persistent object (PO) corresponding to various data tables, the interface (DAO) for operating the database, and the corresponding XML bound to the Dao. These are repetitive operations that do not require much technical content. At this time, we can’t help thinking, is there a tool that can help us automatically generate these files? The answer is: Yes!

The following content of this article is mainly applicable to the development of persistence layer framework using mybatis. If you don’t use mybatis, this article may not be suitable for your development scenario.

Introduction to mybatis generator

As an independent tool based on mybatis, mybatis generator can meet our above requirements. It can help us generate Po, Dao, XML and other files corresponding to the data table through simple configuration, minus the time we manually generate these files, so as to effectively improve the development efficiency. Mybatis generator operates in various ways, mainly through the following ways:

  1. command line
  2. Ant
  3. Maven
  4. Java
  5. Eclipse

I usually configure and use it in maven, so this article mainly explains it based on Maven environment.

preparation

Introducing plug-ins

Since you want to use mybatis generator, you must have configured the database and related dependencies of mybatis in our project. If not, you canpom.xmlFile, mainly taking MySQL database as an example.

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
    </dependency>
</dependencies>

Next, we continue to introduce the related configuration of mybatis generator.

<build>
    <plugins>
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.4.0</version>
        </plugin>
    </plugins>
</build>

Plug in configuration

After completing the above steps, we just completed the introduction of mybatis generator. To make it work normally, we need to configure it, and mybatis generatorpom.xmlThe main configurations in are as follows.

  1. The path to the configuration file for the code generator

Here, we mainly configure the path where the mybatis generator configuration file is located. Generally, we put it inresourcesPath, and the name of the configuration file can be customized. Here Imybatis-generator-config.xmlFor example, you need to add the following configuration topom.xmlFile.

<configuration>
    <configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile>
</configuration>

Mybatis generator code automatic generator, free your hands from now on

  1. Overwrite generated files after each new generation

Due to the project requirements, it is assumed that new fields need to be added in our database table, and we have used mybatis generator to generate relevant files before. At this time, if we want to add the newly added fields to the original generated file, the first way is to delete the old file manually and then regenerate it. The second is to configure it in mybatis generator so that each newly generated file directly overwrites the old file. The specific configuration is as follows:,trueRepresents coverage,falseThen it means that it is not overwritten.

<configuration>
    <overwrite>true</overwrite>
</configuration>

However, it should be noted that even if we set to overwrite the old files, mybatis generator will only overwrite the original Po and Dao files. At this time, mapper will not be overwritten, but will be appended to ensure that the SQL statements we add will not be overwritten.

  1. Database driven dependency

Although in the projectpom.xmlIn the file, we have configured the related dependencies of the database, but we still need to configure it again in the mybatis generator configuration. At this point, there are two ways for us to choose.

The first is to introduce database dependency again. The specific configuration method is as follows:

<build>
    <plugins>
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.4.0</version>
            <dependencies>
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>8.0.17</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

The second is to use Maven’sincludeCompileDependenciesProperties. Generally speaking, we must have introduced database dependency in our project, so let’s configure it at this timeincludeCompileDependenciesJust fine. The specific configuration method is as follows:

<configuration>
    <includeCompileDependencies>true</includeCompileDependencies>
</configuration>

Mybatis generator configuration

We have introduced mybatis generator in the above steps, and also in the project configuration filepom.xmlThe path where the mybatis generator configuration file is located, whether to overwrite the file and database dependency configuration are configured in. Next, let’s take a specific look at how to configure mybatis generator and configure various details in our generated code.

  1. External profile

Generally, we need to import external files, which are mainly used to configure the project database to facilitate our subsequent settings. The method of importing external configuration files is also very simple. The specific configuration is as follows:

<generatorConfiguration>
    <!--  Import profile -- >
    <properties resource="generator.properties"/>
</generatorConfiguration>
  1. Context configuration

In addition to external configuration,contextIt is undoubtedly the most important configuration in mybatis generator. OnecontextSpecific examples of configuration are as follows:

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

The meanings of each attribute are as follows:

  • id: unique identification, non repeatable, can be customized according to our own preferences.
  • defaultModelType: not required. There are two optional values, one isconditional, which is also the default value. The other value isflat, which is a commonly used configuration. It means that a table in the database generates a PO correspondingly.
  • targetRuntime: not required. There are also two optional values here. One isMyBatis3, one isMyBatis3Simple, the main difference between the two is that the Dao and mapper generated under different configurations will be different. The latter will generate much less Dao and mapper and only contain the most commonly used ones.

contextIn addition to the above configuration, there are many sub elements to be configured, and the number and order of these sub elements are specified. If they are not configured according to the given rules, errors will be caused. The common sub elements and number configuration are as follows (sorted from top to bottom according to the specified order):

Child element Minimum number Maximum number
property 0 N
plugin 0 N
commentGenerator 0 1
jdbcConnection
javaTypeResolver 0 1
javaModelGenerator 1 N
sqlMapGenerator 0 1
javaClientGenerator 0 1
table 1 N

Next, we will explain the configuration of each sub element in turn.

Context sub element configuration

  1. property

If we want to set the encoding type of our generated file, we can configure it here. The specific configuration is as follows:

<property name="javaFileEncoding" value="UTF-8"/>
  1. plugin

The Po generated by default contains only the attribute declarations and the corresponding attributessetter/getter, if we want to generate the corresponding PoequalsandhashCodeMethod can be implemented by configuring the following plug-ins.

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

To generatetoStringMethod, you can use the following plug-ins:

<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>

To generate serialization methods for the model, use the following plug-ins:

<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
  1. commentGenerator

This configuration is mainly used to configure generated comments. By default, comments will be generated with time stamps. If we don’t need these configurations, we can clear them through the following configuration:

<commentGenerator>
    <!--  Whether to remove automatically generated comments true: Yes: false: no -- >
    <property name="suppressAllComments" value="true"/>
    <!--  Remove automatically generated timestamp true: Yes: false: no -- >
    <property name="suppressDate" value="true"/>
    <!--  Whether to add comments to fields in the database table true: Yes: false: No, only when suppressallcomments is false can it take effect -- >   
    <property name="addRemarkComments" value="true"/>
</commentGenerator>
  1. jdbcConnection

Since we want to automatically generate the corresponding file, we must link the database, so we need to configure the database. As mentioned above, we can import the external configuration file. In this way, we can define the database configuration in the external file, and then import the file for configuration. The specific steps are as follows:

<jdbcConnection driverClass="${jdbc.driver-class-name}"
                connectionURL="${jdbc.url}"
                userId="${jdbc.username}"
                password="${jdbc.password}">
    <!-- Higher versions of MySQL connector Java need to set nullcatalogmeanscurrent = true -- >
    <property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
  1. javaTypeResolver

It is mainly used to configure the type conversion rules in JDBC and Java. If we do not configure it, the default set of conversion rules will be adopted. If we need to customize it, we can only configure itbigDecimalNUMERICAnd time types. Other types cannot be configured, otherwise errors will occur. The specific configuration rules are as follows:

<javaTypeResolver>
    <property name="forceBigDecimals" value="true"/>
    <property name="useJSR310Types" value="false"/>
</javaTypeResolver>
  • forceBigDecimals

This attribute defaults tofalse, it will JDBCDECIMALandNUMERICType resolves toInteger, if the attribute istrue, JDBC will beDECIMALandNUMERICType resolves tojava.math.BigDecimal

  • useJSR310Types

This attribute defaults tofalse, it resolves all JDBC time types tojava.util.Date, if the attribute istrue, it will be parsed according to the following rules:

Before conversion After conversion
DATE java.time.LocalDate
TIME java.time.LocalTime
TIMESTAMP java.time.LocalDateTime
TIME_WITH_TIMEZONE java.time.OffsetTime
TIMESTAMP_WITH_TIMEZONE java.time.OffsetDateTime
  1. javaModelGenerator

This is mainly used to configure the package path and project path of the automatically generated Po. It needs to be configured according to your own needs. Here, take my own configuration as an example, for example, the package of my Po iscom.cunyu1943.mybatisgeneratordemo.entity, project path issrc/main/java

<javaModelGenerator targetPackage="com.cunyu1943.mybatisgeneratordemo.entity" targetProject="src/main/java">
    <!--  Whether to use schema as the suffix of the package. The default is false -- >
    <property name="enableSubPackages" value="false"/>
    <!--  Whether to trim the field of string type in the set method. The default is false -- >
    <property name="trimStrings" value="true"/>
</javaModelGenerator>
  1. sqlMapGenerator

Configure generatedMapper.xmlThe stored path, such as where we want to putsrc/main/resources/mapperUnder path, the configuration is as follows:

<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
</sqlMapGenerator>
  1. javaClientGenerator

to configureMapperThe path stored by the interface is generally stored in the projectmapperUnder the package, if my configuration is:

<javaClientGenerator targetPackage="com.cunyu1943.mybatisgeneratordemo.mapper" targetProject="src/main/java"
                     type="XMLMAPPER">
</javaClientGenerator>
  1. table

Configure the database table to automatically generate code. Here, one table corresponds to onetable, if you want to generate multiple tables, you need to configure multiple tablestable, the following is a specific example:

<table schema="" tableName="user" domainObjectName="User"
       enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
       enableUpdateByExample="false" selectByExampleQueryId="false">
    <!-- Whether to use the actual column name. The default is false -- >
    <property name="useActualColumnNames" value="false" />
</table>

Among them,schemaIt is the database name. Some databases need to be configured and some databases do not need to be configured. It needs to be filled in here according to the database you use, but it is recommended to fill in all, so that different databases can also be applied.tableNameThe corresponding database table name;domainObjectNameCorresponding to the generated entity class name, it can not be configured by default. When it is not configured, it will convert the indication into class name according to Pascal naming method; andenableXXXByExampleDefault totrue, one is generated by defaultExampleHelp class, but this configuration is only available intargetRuntime="MyBatis3"It can only take effect whentargetRuntime="MyBatis3Simple"When,enableXXXByExampleConfiguration does not work anyway.

Execute build

After the above configuration, we get the overall mybatis generator configuration. The complete configuration is as follows. You can modify the configuration according to your own needs and then use it.

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

<generatorConfiguration>
    <!--  Import profile -- >
    <properties resource="generator.properties"/>

    <!--  A database has a context, and the child elements of the context must be in the order given by it
        property*,plugin*,commentGenerator?,jdbcConnection,javaTypeResolver?,
        javaModelGenerator,sqlMapGenerator?,javaClientGenerator?,table+
    -->
    <context id="myContext" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <!--         Set the encoding of the generated file -- >
        <property name="javaFileEncoding" value="UTF-8"/>

        <!--  This plug-in adds equals and hashcode methods to the generated Java model object -- >
        <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
        <!--         Add toString method -- >
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
        <!--         Generate serialization method -- >
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>

        <!--  Notes -- >
        <commentGenerator>
            <!--  Generate comments: true: No: false: yes -- >
            <property name="suppressAllComments" value="true"/>
            <!--  Remove timestamp: true: Yes: false: no -- >
            <property name="suppressDate" value="true"/>
            <!--  Whether to add comments to fields in the database table true: Yes: false: No, only when suppressallcomments is false can it take effect -- >
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>


        <!--  JDBC connection -- >
        <jdbcConnection driverClass="${jdbc.driver-class-name}"
                        connectionURL="${jdbc.url}"
                        userId="${jdbc.username}"
                        password="${jdbc.password}">
            <!-- Higher versions of MySQL connector Java need to set nullcatalogmeanscurrent = true -- >
            <property name="nullCatalogMeansCurrent" value="true"/>
        </jdbcConnection>

        <!--  Type conversion -- >
        <javaTypeResolver>
            <!-- Whether to use BigDecimal. The default is false.
                False, resolve JDBC decimal and numeric types to integer
                True, resolve JDBC decimal and numeric types to Java math. BigDecimal-->
            <property name="forceBigDecimals" value="true"/>
            <!-- Default false
                False, resolve all JDBC time types to Java util. Date
                True, resolve the JDBC time type according to the following rules
                    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.cunyu1943.mybatisgeneratordemo.entity" targetProject="src/main/java">
            <!--  Whether to use schema as the suffix of the package. The default is false -- >
            <property name="enableSubPackages" value="false"/>
            <!--  Whether to trim the field of string type in the set method. The default is false -- >
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>


        <!--  Generate mapper XML file -- >
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
        </sqlMapGenerator>

        <!--  Generate xxmapper Java interface -- >
        <javaClientGenerator targetPackage="com.cunyu1943.mybatisgeneratordemo.mapper" targetProject="src/main/java"
                             type="XMLMAPPER">
        </javaClientGenerator>


        <!--  Schema is the database name, which needs to be configured in Oracle and not in MySQL.
             Tablename is the corresponding database table name
             Domainobjectname is the name of the entity class to be generated (it can not be specified. By default, the table name is converted into class name according to Pascal naming method)
             Enablexxxbyexample defaults to true. If it is true, a corresponding example help class will be generated to help you query conditions. If you don't want to, it can be set to false
             -->
        <table schema="" tableName="user" domainObjectName="User"
               enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
               enableUpdateByExample="false" selectByExampleQueryId="false">
            <!-- Whether to use the actual column name. The default is false -- >
            <property name="useActualColumnNames" value="false"/>
        </table>
    </context>
</generatorConfiguration>

Among them, about external filesgenerator.propertiesThe configuration of is as follows. It mainly configures the relevant attributes of the database.

jdbc.username=root
jdbc.password=123456
jdbc.url=jdbc:mysql://localhost:3306/community?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
jdbc.driver-class-name=com.mysql.cj.jdbc.Driver

Finally, when all the configuration is completed, you can use Maven tool for code generation. The specific operation method is as follows: Click mybatis generator in Maven configuration of the project to generate.

Mybatis generator code automatic generator, free your hands from now on

summary

The above is to use Maven and mybatis generator to configure and generate project Po, mapper and xxxmapper The specific construction process of XML. If you happen to have this demand, try it quickly. If you encounter any problems during the construction process, please leave a message in the comment area and I will reply as soon as I see it.

Finally, I have passed the relevant code of this example to GitHub. If you need a brother, you can get it yourself.

Portal – > mybatis generator demo

Recommended Today

Behavior type: X Visitor mode

What is the visitor pattern Visitor is a behavioral design pattern that allows you to add new behaviors to the existing class hierarchy without modifying the existing code. Why use visitor mode Visitor pattern suggests putting new behavior into a separate class called visitor rather than trying to integrate it into existing classes. Now the […]