One minute to learn how to use mybatis generator to generate code automatically!

Keywords: Java Mybatis xml MySQL

Catalog

Previous articles SpringBoot series - integrating Mybatis (XML configuration mode) This paper introduces the process of XML configuration integration, and introduces the process of generating XML, dao and entity by using mybatis generator.

I. Introduction to MyBatis Generator

MyBatis Generator is a code generator officially provided by MyBatis, which can generate xml, dao and entity.

See http://mybatis.org/generator for the official website/

II. Usage

MyBatis Generator can be used in four ways:

  • Command line generation
  • Maven mode generation
  • Build with Ant task
  • Using Java code generation

This article will use Intel IDEA+Maven method to generate code, because integration and use are relatively simple, after configuration, double-click directly to run.

Three, actual combat

First, create a new spring boot project, spring mybatis generator, and then follow the steps below.

  1. Configure plugin in pom.xml
<!-- Introduce mybatis-generator Plug-in unit -->
<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.2</version>
    <configuration>
        <!-- mybatis-generator The configuration file of, adjust the location according to the situation -->
        <configurationFile>src/main/resources/mybatis-generator.xml</configurationFile>
        <verbose>true</verbose>
        <overwrite>true</overwrite>
    </configuration>
    <executions>
        <execution>
            <id>Generate MyBatis Artifacts</id>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>
    </dependencies>
</plugin>
  1. Modify mybatis-generator.xml file

In the previous step, a configuration file was specified in pom.xml. Therefore, create mybatis-generator.xml in the resources directory. Through this configuration file, MyBatis Generator can perform the following operations:

  • How to connect to a database
  • What objects to generate and how to generate them
  • Which tables apply to object generation

There will be the complete contents below, and it should be noted that.

The path of JDBC Driver jar must be absolute.
The path of JDBC Driver jar must be absolute.
The path of JDBC Driver jar must be absolute.

Say important things three times.

The complete contents of mybatis-generator.xml are as follows:

<?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>

    <!--JDBC drive jar Absolute path of package -->
    <!--JDBC drive jar Absolute path of package -->
    <!--JDBC drive jar Absolute path of package -->
    <classPathEntry location="C:\Users\java_suisui\.m2\repository\mysql\mysql-connector-java\5.1.39\mysql-connector-java-5.1.39.jar"/>

    <!--defaultModelType="flat" Big data field, regardless of table -->
    <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="autoDelimitKeywords" value="true" />
        <property name="beginningDelimiter" value="`" />
        <property name="endingDelimiter" value="`" />
        <property name="javaFileEncoding" value="utf-8" />
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />

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

        <!-- Notes -->
        <commentGenerator >
            <property name="suppressAllComments" value="true"/><!-- Cancel comment or not -->
            <property name="suppressDate" value="true" /> <!-- Generate comment generation timestamp or not-->
        </commentGenerator>

        <!--Database link address account password-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/demo"
                        userId="root"
                        password="123456">
        </jdbcConnection>

        <!-- Type conversion -->
        <javaTypeResolver>
            <!-- Whether to use bigDecimal, false The following types can be automatically converted( Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!--generate Model Class storage location-->
        <javaModelGenerator targetPackage="com.example.springbootmybatis.generator.entity" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- generate mapxml file -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources" >
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>

        <!-- generate mapxml Corresponding client,Interface dao -->
        <javaClientGenerator targetPackage="com.example.springbootmybatis.generator.dao" targetProject="src/main/java" type="XMLMAPPER" >
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

        <table tableName="user" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="true">
            <generatedKey column="id" sqlStatement="Mysql" identity="true" />
        </table>

        <table tableName="user_role" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="true">
            <generatedKey column="id" sqlStatement="Mysql" identity="true" />
        </table>

    </context>
</generatorConfiguration>
  1. Generate code

Click "Maven Projects" on the right side of IntelIDEA, find mybatis generator: generate under spring boot mybatis generator, double-click to run, and "BUILD SUCCESS" appears in the log to indicate that the code has been generated.

Running screenshot:

Generate code screenshot:

Operation log:

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building spring-boot-mybatis-generator 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- mybatis-generator-maven-plugin:1.3.2:generate (default-cli) @ spring-mybatis-generator ---
[INFO] Connecting to the Database
[INFO] Introspecting table user
log4j:WARN No appenders could be found for logger (org.mybatis.generator.internal.db.DatabaseIntrospector).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
[INFO] Introspecting table user_role
[INFO] Generating Record class for table user
[INFO] Generating Mapper Interface for table user
[INFO] Generating SQL Map for table user
[INFO] Generating Record class for table user_role
[INFO] Generating Mapper Interface for table user_role
[INFO] Generating SQL Map for table user_role
[INFO] Saving file UserMapper.xml
[INFO] Saving file UserRoleMapper.xml
[INFO] Saving file User.java
[INFO] Saving file UserMapper.java
[INFO] Saving file UserRole.java
[INFO] Saving file UserRoleMapper.java
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

Now we have finished the introduction of using mybatis generator to generate code automatically. If you have any questions, please leave a message and communicate!

Full source address: https://github.com/suisui2019/springboot-study

Recommended reading
1. Take your hands on Spring's seven transaction communication behaviors in practice

2.SpringBoot series - integrate Mybatis (annotation method)

3.SpringBoot series - integrate Mybatis (XML configuration mode)

4. Printing logs in Java is very important!

5. Spring boot integrates JWT to realize permission authentication

Collect free Java related materials in limited time, covering Java, Redis, MongoDB, MySQL, Zookeeper, Spring Cloud, Dubbo/Kafka, Hadoop, Hbase, Flink and other high concurrent distributed, big data, machine learning and other technologies.
Pay attention to the public numbers below for free.

This article is based on the platform of blog one article multiple sending OpenWrite Release!

Posted by basdog22 on Fri, 15 Nov 2019 00:49:11 -0800