The use of reverse engineering in Mybatis Generator


1, About MyBatis Generator

MyBatis Generator (MBG) is the code generator of MyBatis and iBATIS. It will generate code for all versions of MyBatis and versions of iBATIS after 2.2.0. It reviews database tables (or many tables) and generates artifacts that can be used to access tables. This reduces the initial hassle of setting up objects and configuration files to interact with database tables. MBG seeks to have a significant impact on most database operations for simple CRUD (create, retrieve, update, delete). You still need to manually write SQL and object code for connection queries or stored procedures. MyBatis Generator will generate:

  • Java POJO that matches the table structure. This may include:

    • A class matching the primary key of the table (if there is a primary key)

    • A class that matches a table's non primary key fields (except BLOB fields)

    • Class containing the table's BLOB field (if the table has a BLOB field)

    • Classes for enabling dynamic selection, updating, and deletion

There is an appropriate inheritance relationship between these classes. Note that the generator can be configured to generate different types of POJO hierarchies - for example, you can choose to generate a single domain object for each table, if you like.

  • MyBatis/iBATIS compatible SQL Map XML file. MBG generates SQL for simple CRUD functions on each table in the configuration. The generated SQL statements include:

    • Insert insert

    • update by primary key

    • update by example (using a dynamic where clause)

    • delete by primary key

    • delete by example (using a dynamic where clause)

    • select by primary key

    • select by example (using a dynamic where clause)

    • count by example

Depending on the table structure, these statements have different variations (for example, if the table does not have a primary key, MBG does not generate updates through the primary key function).

    • Use the Java client class of the above object appropriately. Generation of java client classes is optional. MBG will generate the following types of Java clients for MyBatis 3.x:

      • Mapper interface for MyBatis 3.x mapper infrastructure

MBG will generate the following types of Java clients for iBATIS 2.x:

    • DAO conforming to Spring framework

    • DAO using iBATIS SQL mapping API only. These Daos can generate two types: SqlMapClient through constructor or setter injection.

    • DAO conforming to iBATIS DAO framework (optional part of iBATIS, not recommended now, we suggest you use Spring framework)

The MyBatis generator is designed to work well in an iterative development environment and can be included as an Ant task or as a Maven plug-in in a continuous build environment. The important points to be noticed when running MBG iteratively include:

  1. If there is an existing file with the same name as the newly generated XML file, MBG will automatically merge the XML file. MBG does not overwrite any custom changes you make to the XML file it generates. You can run it over and over without worrying about losing custom changes to XML. MBG will replace any XML elements generated in the previous run.

  2. MBG does not merge Java files, it can overwrite existing files or save newly generated files with different unique names. If you make changes to the generated Java file and run MBG iteratively, you must merge the changes manually. When run as an Eclipse plug-in, MBG can automatically merge Java files.

2, MyBatis Generator uses

1. New MBG profile generatorConfig.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-// MyBatis Generator Configuration 1.0//EN"
    <!--Import property configuration-->
    <properties resource=""></properties>
    <!--Specify the jdbc drive jar Package location-->
    <!--<classPathEntry location="${jdbc.driverLocation}"/>-->
    <context id="default" targetRuntime="MyBatis3">
        <!-- optional,Designed to create class Control the comments, false Generate comments,true No comment -->
            <property name="suppressDate" value="false"/>
            <property name="suppressAllComments" value="false"/>
        <!--jdbc Database connection for -->
         //The default is false, which resolves JDBC DECIMAL and NUMERIC types to Integer,
         //When true, the JDBC DECIMAL and NUMERIC types are resolved to java.math.BigDecimal
        <!-- Not required, type processor, in database type and java Conversion control between types-->
            <property name="forceBigDecimals" value="false"/>
        <!-- Model Model builder,Used to generate a primary key key Class, record class and query of Example class
            targetPackage     Specify generated model Package name where the build is located
            targetProject     Specify the path under the project|Specify the project name to build to
        <javaModelGenerator targetPackage="com.test.model"
            <!-- Whether subpackages are allowed, i.e targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- Yes no model Add constructor true add to, false Do not add-->
            <property name="constructorBased" value="false"/>
            <!-- Whether to class CHAR Type of column trim operation -->
            <property name="trimStrings" value="true"/>
            <!-- Established Model Whether the object is immutable or not Model Object will not have setter Method, only construction method -->
            <property name="immutable" value="false"/>
        <!--Mapper The directory where the mapping file is generated generates the corresponding SqlMapper file -->
        <sqlMapGenerator targetPackage="com.test.mapper"
            <property name="enableSubPackages" value="false"/>
        <!-- Client code, easy to use for Model Objects and XML Code for profile
                type="ANNOTATEDMAPPER",generate Java Model And annotation based Mapper object
                type="MIXEDMAPPER",Generate annotation based Java Model And the corresponding Mapper object
                type="XMLMAPPER",generate SQLMapper XML Documentation and independent Mapper Interface
        <javaClientGenerator targetPackage="com.test.mapper"
                             targetProject=".\src\main\java" type="XMLMAPPER">
            <property name="enableSubPackages" value="true"/>
        <!--Table name of the database to be mapped-->
        <table tableName="t_userinfo" domainObjectName="UserInfo"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"

2. New file


3. There are two ways to configure the operation of mybatis generator

Method 1: if you use maven project, you can save writing Java startup classes, use maven plug-ins and configuration files pom.xml That is, the plug-in starts the maven generator, and pom.xml Add maven generator plug-in to

    <!--myBatis Reverse engineering plug in-->

Click on mybatis-generator:generate You can execute mybatis generator

The second way:

1. If it is not for maven project to add the mybatis-generator-core-1.3.2.jar and write the main method to point to mybatis reverse engineering, I pasted the dependency below

<!-- -->

2. Modification generatorConfig.xml File, release this configuration for comment

<classPathEntry location="${jdbc.driverLocation}"/>

3. Then write a test class to execute

 * If it's not a maven project, you can build it like this
public class MybatisGeneratorTest {
    public static void main(String[] args) throws InterruptedException, SQLException, IOException, InvalidConfigurationException, XMLParserException {
        List<String> warnings = new ArrayList<String>();
        //Generated java Whether the file is overwritten
        boolean overwrite = true;
        //Specify reverse engineering profile
        //File configFile = new File("E:\\project\\mybatis-generator\\src\\main\\resources\\generatorConfig.xml");
        InputStream resourceAsStream = MybatisGeneratorTest.class.getClassLoader().getResourceAsStream("generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(resourceAsStream);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,callback, warnings);

After introducing the two methods, check the data table:

To view the generated entity class:

TIP: it can be seen that if the entity class wants to follow the hump naming specification, the database table field name design needs to use the_ "To divide

To view the generated file information:

TIP1: the database driver must be added in the < plugin > < / plugin > tag. It is invalid to add it elsewhere. If it is not added, the driver error will be reported. If it is not added, the < classpathentry location = "can be used${ jdbc.driverLocation }"/ > to specify the database drive location.

TIP2: if you use the mybatis generator plug-in to execute, report [error] failed to execute goal org.mybatis.generator :mybatis-generator-maven- plugin:1.3.2 :generate (default-cli) on project mybatis-generator: <properties> resource does not exist -> [Help 1]

Although your < properties resource=“ "> < / Properties > configuration is OK, but we still can't find it , view the configuration and comment out

This configuration will change generatorConfig.xml Read in Default path for files

TIP3: by default, the generated *. java files will not be overwritten by the reverse engineering of Mybatis Generator. You can also set the *. java file generated by overwriting. Adding the configuration in the reverse engineering plug-in Mybatis Generator Maven plugin < overwrite > true < / overwrite > will overwrite the generated *. java file, as shown in the figure

    Mybatis Generator won't overwrite you mapper.xml File, MBG will merge and append to mapper.xml With the existence of your customization, but if you modify the SQL (CRUD generated by MBG) generated by MBG by default for the first time, MBG will restore the CRUD generated by itself to the default. Frankly, MBG will only overwrite the SQL generated by itself, and will not overwrite your customization, and your customization will remain the same... As shown in the figure, it will not move your custom SQL, but will only overwrite the SQL generated by mybatis reverse engineering itself, provided that the annotation of the SQL statement automatically generated by MBG exists.

In the most common use case, the MyBatis Generator (MBG) is driven by an XML configuration file. Profile tells MBG

  • How to connect to a database

  • What objects to generate and how to generate them

  • Which tables should be used to build objects

Official MBG profile details address:

A detailed explanation of MBG's Chinese configuration file is attached:


For more use of Mybatis reverse engineering, please refer to:

● XStream learning manual

● Don't log in Java code, this is the right way to log!

● Analysis and construction of highly available Redis service architecture

● 8 solutions, help you to solve the problem of repeated submission!Please take it away

Is this article enough for IDEA to solve Maven's high-energy artifact that relies on conflict?

Keywords: Java Mybatis xml JDBC

Added by Doyley on Fri, 19 Jun 2020 06:20:27 +0300