MyBatis Generator – quickly generate entity classes and mapping files

Table of Contents

1. Use of MyBatis Generator

1.1. Generate class and mapping files

1.1.1. Introduce dependencies in pom.xml

1.1.2. Create the generatorConfig.xml file according to the path configured in the configurationFile tag.

1.1.3. Automatically generate classes and mapping files

1.1.4. Add the option to obtain the primary key value in the Insert tag

1.1.5. Scanning configuration: add @Mapper annotation / add scanning annotation

1.1.6. Configure mybatis

1.1.7. Testing


1. Use of MyBatis Generator

1.1. Generate classes and mapping files

1.1.1, introduce dependencies in pom.xml

Add the version number to the properties tag.

<mybatis-generator-plugin-version>1.4.1</mybatis-generator-plugin-version>

Add the following configuration to the build => plugins tag

 <!-- mybatis ?generator plug-in -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>${mybatis-generator-plugin-version}</version>
                <executions>
                    <execution>
                        <id>Generate MyBatis Artifacts</id>
                        <phase>deploy</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <!-- Related configuration -->
                <configuration>
                    <!-- Open the journal -->
                    <verbose>true</verbose>
                    <!-- Allow override -->
                    <overwrite>true</overwrite>
                    <!-- Configure file path -->
                    <configurationFile>
                        src/main/resources/mybatis/generatorConfig.xml
                    </configurationFile>
                </configuration>
            </plugin>

What needs to be noted in the above configuration is the “configuration file path”, which is the location used to generate entity class and mapping file configuration rules.

1.1.2. Create the generatorConfig.xml file according to the path configured in the configurationFile tag

This file is used to describe the generation rules.

According to the path (src/main/resources/mybatis), create the generatorConfig.xml file in the mybatis directory.

Ps: The following configuration files need to be modified: database connections, paths to entity classes and mapping files, and database table names.

<?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>
    <!-- Driver package path, replace the path in location with the local path -->
    <classPathEntry location="D:\class\source\mysql-connector-java-5.1.49.jar"/>

    <context id="DB2Tables" targetRuntime="MyBatis3">
        <!-- Comments on the prohibition of movement -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
        </commentGenerator>
        <!-- Connection configuration -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/javanav_db?
characterEncoding=utf8 &amp;useSSL=false"

                        userId="root"

                        password="1111">
        </jdbcConnection>
        <javaTypeResolver>
            <!-- ?Convert numbers to BigDecimal -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- Entity class creation position -->
        <javaModelGenerator targetPackage="com.example.cyk.model"

                            targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- mapper.xml? into location -->
        <sqlMapGenerator targetPackage="mapper"

                         targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- mapper interface configuration location -->
        <javaClientGenerator type="XMLMAPPER"

                             targetPackage="com.example.cyk.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!-- To configure tables and instances, you only need to modify the table name, tableName, and the corresponding class name, domainObjectName, that is
       Can -->
        <table tableName="j_article" domainObjectName="Article"

               enableSelectByExample="false"

               enableDeleteByExample="false" enableDeleteByPrimaryKey="false"

               enableCountByExample="false"

               enableUpdateByExample="false">
            <!-- The attribute of the class is the real field name in the database as the attribute name. If this attribute is not specified, it will be automatically converted _ to
           Camel case naming rules -->
            <property name="useActualColumnNames" value="true"/>
        </table>
        <table tableName="j_article_reply" domainObjectName="ArticleReply"

               enableSelectByExample="false"

               enableDeleteByExample="false" enableDeleteByPrimaryKey="false"

               enableCountByExample="false"

               enableUpdateByExample="false">
            <property name="useActualColumnNames" value="true"/>
        </table>
        <table tableName="j_board" domainObjectName="Board"

               enableSelectByExample="false" enableDeleteByExample="false"

               enableDeleteByPrimaryKey="false" enableCountByExample="false"

               enableUpdateByExample="false">
            <property name="useActualColumnNames" value="true"/>
        </table>
        <table tableName="j_message" domainObjectName="Message"

               enableSelectByExample="false"

               enableDeleteByExample="false" enableDeleteByPrimaryKey="false"

               enableCountByExample="false"

               enableUpdateByExample="false">
            <property name="useActualColumnNames" value="true"/>
        </table>
        <table tableName="j_user" domainObjectName="User"

               enableSelectByExample="false" enableDeleteByExample="false"

               enableDeleteByPrimaryKey="false" enableCountByExample="false"

               enableUpdateByExample="false">
            <property name="useActualColumnNames" value="true"/>
        </table>
    </context>
</generatorConfiguration>

Notice:

The driver package path is the path of your own local warehouse

But be sure to pay attention! ! It needs to be in a non-Chinese directory, so you can copy this driver package and put it in a non-Chinese directory.

1.1.3, automatically generate classes and mapping files

Reload the Maven project, mybatis-generator appears under the Plugins node, double-click the run, and generate the corresponding class and mapping files in the corresponding directory:

Then you can see the corresponding generation

1.1.4. Add the option to obtain the primary key value in the Insert tag

In the generated xml file, add the following attributes to each insert tag: useGeneratedKeys=”true” keyProperty=”id”

<!-- useGeneratedKeys = true -->
<!-- keyProperty = primary key field-->

<!-- After inserting a piece of data, you can get the Id value automatically generated through user.getId(). If you need to get the Id value immediately in the method, add this configuration -->
<insert id="insert" parameterType="com.example.cyk.model.User"
useGeneratedKeys="true" keyProperty="id" >

Ps: This option can also be automatically generated, but it is not ideal (some problems)

1.1.5. Scanning configuration: Add @Mapper annotation/Add scanning annotation

There are two ways to configure scanning Mapper interfaces.

1) Add the @Mapper annotation to the mapper interface under each mapper package.

2) Add the @MapperScan(“com.example.cyk.mapper”) annotation to the startup class or create a new configuration class (with @Configuration annotation).

1.1.6, configure mybatis

Configure in yml file

mybatis:
  mapper-locations: classpath:mapper/**/*Mapper.xml

1.1.7, test

@SpringBootTest
public class TestMapper {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void select() {
        User user = userMapper.selectByPrimaryKey(1L);
        System.out.println(user);
    }

}

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 138128 people are learning the system