Stop handwriting entity classes and Mappers, use MyBatis code generation tool to generate one-click!

MyBatis code generation tool

In the process of using MyBatis, we often need to write entity classes and single-table CRUD code. When there are not many tables, it may be okay, but once there are too many tables, it will be quite troublesome. Fortunately, the official MyBatis code generator (MyBatis Generator) can help us solve this problem. MyBatis Generator (MBG) can directly generate entity classes, single-table CRUD codes, and mapper.xml files through database tables. Let's take a look at how to use MyBatis Generator.


Use MyBatis Generator

1. Add dependencies

Using MBG is mainly based on the following two dependencies, one is the spring boot dependency of mybatis and the dependency of MyBatis Generator. If you just want to use the MyBatis code generator, you can even not rely on mybatis-spring-boot-starter

    <!--SpringBoot整合MyBatis-->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.0</version>
    </dependency>

    <!-- MyBatis 生成器 -->
    <dependency>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-core</artifactId>
        <version>1.4.0</version>
    </dependency>

    <!--Mysql数据库驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>

2. After adding a dependency, we need to perform related configuration

Configure the data source and MyBatis mapper.xml file path in application.yml

#数据库连接
spring.datasource.url=jdbc:mysql://192.168.91.128:3306/mytest?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#指定本地mapper.xml文件的存放位置
mybatis.mapper-locations=classpath:dao/*.xml

3. Add the @MapperScan annotation to the startup class and specify the scan path

The path can be as long as it contains your Mapper interface. The smaller the range, the higher the efficiency.

@MapperScan("com.example.demo2")
public class Demo2Application {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(Demo2Application.class, args);
    }

}

4. Mybatis is configured above, and then we can write the xml configuration file of the code generator in the resources directory

Below is a code generator xml file I wrote

The name is: generatorConfig.xml

The content is 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>
    <!--
        context:代码生成规则配置的上下文
            id:标识
            targetRuntime: MyBatis3Simple 只会生成基本的CRUD操作

    -->
    <context id="DB2Tables" targetRuntime="MyBatis3Simple">

        <!--commentGenerator:注释生成策略-->
        <commentGenerator>
            <!--suppressAllComments:是否阻止注释生成-->
            <property name="suppressAllComments" value="true"/>
            <!--suppressDate:是否阻止时间戳生成-->
            <property name="suppressDate" value="true"/>
        </commentGenerator>

        <!--jdbcConnection:数据库的链接属性-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mytest?useUnicode=true&amp;characterEncoding=utf8"
                        userId="root"
                        password="root">
            <!--解决mysql驱动升级到8.0后不生成指定数据库代码的问题-->
            <property name="nullCatalogMeansCurrent" value="true" />
        </jdbcConnection>

        <!--javaTypeResolver:java类型转换策略-->
        <javaTypeResolver >
            <!-- forceBigDecimals
                 false:如果数据库中的字段类型为numeric或者decimal,在代码生成的时候根据数据库中设定的长度自动选择java类型进行转换
                 true:直接使用java.math.BigDecimal类型-->
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!--domain生成策略;targetPackage:生成到哪个包下面,targetProject:生成到哪个项目目录下面-->
        <javaModelGenerator targetPackage="com.example.childdemo.model" targetProject="src/main/java">
            <!--<property name="enableSubPackages" value="true" />-->
            <!--表示是否修剪字符串(去掉空格-->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!--sqlMapGenerator:映射文件生成策略
               targetPackage:生成到哪个包下面,targetProject:生成到哪个项目目录下面
        -->
        <sqlMapGenerator targetPackage="com.example.childdemo.mapper"  targetProject="src/main/resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!--mapper接口生成策略
           type:ANNOTATEDMAPPER:注解的形式
                XMLMAPPER:xml映射的形式-->
        <javaClientGenerator type="ANNOTATEDMAPPER" targetPackage="com.example.childdemo.mapper"  targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!--指定要生成代码的表
                domainObjectName:设置表对应的domain实体类生成的名称
        -->
        <table tableName="productdir" domainObjectName="ProductDir"></table>

    </context>
</generatorConfiguration>`

5. Run the code generator
Let's run the code generator through coding and configuration files

After writing the configuration file, we can write a class to generate code, and run the main method directly to generate all the code. The code is as follows:

public class Generator {
    
    
    public static void main(String[] args) throws Exception {
    
    
        //MBG 执行过程中的警告信息
        List<String> warnings = new ArrayList<String>();
        //当生成的代码重复时,覆盖原代码
        boolean overwrite = true;
        //读取我们的 MBG 配置文件
        InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(is);
        is.close();
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        //创建 MBG
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        //执行生成代码
        myBatisGenerator.generate(null);
        //输出警告信息
        for (String warning : warnings) {
    
    
            System.out.println(warning);
        }
    }

}

Running the main method will help us generate the corresponding entity class and mapper interface


Maven plugin run code generator

In addition to the above methods, we can also run the code generator through the Maven plugin

If you use the Maven plugin, you don't need to introduce the mybatis-generator-core dependency. You only need to introduce a Maven plugin mybatis-generator-maven-plugin. Add the following plugin to the pom file:

             <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <!-- 输出详细信息 -->
                    <verbose>true</verbose>
                    <!-- 覆盖生成文件 -->
                    <overwrite>true</overwrite>
                    <!-- 定义配置文件 -->
                    <configurationFile>${
    
    basedir}/src/main/resources/generator-configuration.xml</configurationFile>
                </configuration>
                <executions>
                    <execution>
                        <id>MyBatis Generate</id>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>

                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.38</version>
                    </dependency>
                </dependencies>
            </plugin>

After the plug-in is configured, use the following command to run:

mvn mybatis-generator:generate

Note: The version of the plug-in must correspond to the version of the connected database, otherwise an error will be reported

We can also run directly in the maven option of the compiler, as follows

Insert picture description here

After running, you can get the corresponding code, as follows

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_36551991/article/details/112440346