[MyBatis] Don't you know how to use MyBatis reverse engineering to improve your development efficiency?

MyBatis reverse engineering

  • Forward engineering: first create a Java entity class, and the framework is responsible for generating database tables based on the entity class (Hibernate supports forward engineering)
  • Reverse engineering: first create the database table, and the framework is responsible for reversely generating Java entity classes, Mapper interfaces, and Mapper mapping files based on the database table

Official documentation: MyBatis Generator

MyBatis官网:mybatis – MyBatis 3 | Introduction

1. Quick start

创建Maven项目
导入依赖
编写MyBatis配置文件
编写逆向工程配置文件
测试
  • Step1 : Create a Maven project

    The directory structure is as follows:

    image-20220911195422947

  • Step2 : import dependencies

    pom.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>org.example</groupId>
        <artifactId>day04_mybatis</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <properties>
            <maven.compiler.source>8</maven.compiler.source>
            <maven.compiler.target>8</maven.compiler.target>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>
    
        <!--添加项目依赖-->
        <dependencies>
            <!--mysql-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.16</version>
            </dependency>
            <!--mybatis-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.10</version>
            </dependency>
            <!--junit-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13.2</version>
                <scope>test</scope>
            </dependency>
            <!--log4j-->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
        </dependencies>
    
        <!--添加项目所需的插件-->
        <build>
            <plugins>
                <!--mybatis逆向工程的插件-->
                <plugin>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-maven-plugin</artifactId>
                    <version>1.3.0</version>
    
                    <!-- 插件的依赖 -->
                    <dependencies>
                        <!-- 逆向工程的核心依赖 -->
                        <dependency>
                            <groupId>org.mybatis.generator</groupId>
                            <artifactId>mybatis-generator-core</artifactId>
                            <version>1.3.2</version>
                        </dependency>
                        <!-- MySQL驱动 -->
                        <dependency>
                            <groupId>mysql</groupId>
                            <artifactId>mysql-connector-java</artifactId>
                            <version>8.0.16</version>
                        </dependency>
                    </dependencies>
                </plugin>
            </plugins>
        </build>
    
    </project>
    
  • Step3 : Write MyBatis configuration file

    jdbc.properties:

    jdbc.driver=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql:///ssm?useSSL=false&characterEncoding=utf8&useServerPrepStmts=true&serverTimezone=UTC
    jdbc.username=root
    jdbc.password=32345678
    

    mybatis-config.xml:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <!--
        MyBatis核心配置文件中,标签的顺序:
        properties?,settings?,typeAliases?,typeHandlers?,
        objectFactory?,objectWrapperFactory?,reflectorFactory?,
        plugins?,environments?,databaseIdProvider?,mappers?
    -->
        <!--引入properties文件-->
        <properties resource="jdbc.properties"/>
        <!--开启一些全局设置-->
        <settings>
            <!--开启格式转换-->
            <setting name="mapUnderscoreToCamelCase" value="true"/>
            <!--开启懒加载-->
            <setting name="lazyLoadingEnabled" value="true"/>
            <!--关闭完整加载-->
            <setting name="aggressiveLazyLoading" value="false"/>
        </settings>
        <!--给实体类所在包起别名,简化书写-->
        <typeAliases>
            <package name="com.hhxy.pojo"/>
        </typeAliases>
        <!--数据库连接环境配置-->
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <!--数据库的连接信息-->
                    <property name="driver" value="${jdbc.driver}"/>
                    <property name="url" value="${jdbc.url}"/>
                    <property name="username" value="${jdbc.username}"/>
                    <property name="password" value="${jdbc.password}"/>
                </dataSource>
            </environment>
        </environments>
        <!--指定SQL映射文件-->
        <mappers>
            <!--使用包扫描方式,简化mapper文件的加载-->
            <package name="com.hhxy.mapper"/>
        </mappers>
    </configuration>
    
  • Step4 : Write reverse engineering files

    generatorConfig.xml:

    <?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>
        <!--	
        targetRuntime: 执行生成的逆向工程的版本,两种取值
            - MyBatis3Simple: 生成基本的CRUD(清新简洁版)
            - MyBatis3: 生成带条件的CRUD(奢华尊享版)
        -->
        <context id="DB2Tables" targetRuntime="MyBatis3Simple">
            <!--定义生成的java类的编码格式-->
            <property name="javaFileEncoding" value="UTF-8"/>
            <!-- 是否去除自动生成的注释 -->
            <commentGenerator>
        	<property name="suppressAllComments" value="true"/>
            </commentGenerator>
            <!-- 数据库的连接信息 -->
            <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                            connectionURL="jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC"
                            userId="root"
                            password="32345678">
            </jdbcConnection>
            <!-- javaBean的生成策略-->
            <!--
            相关配置参数:
            targetPackage:根据数据生成的实体类的包
            targetProject:生成的路径
            enableSubPackages:是否能使用子包(如果是false,则只会解析第一个.,后面的.无法解析,强烈建议设置为true)
            trimStrings:是否去除数据库中表中字段的前后空格
            -->
            <javaModelGenerator targetPackage="com.hhxy.pojo"
                                targetProject=".\src\main\java">
                <property name="enableSubPackages" value="true"/>
                <property name="trimStrings" value="true"/>
            </javaModelGenerator>
            <!-- SQL映射文件的生成策略 -->
            <sqlMapGenerator targetPackage="com.hhxy.mapper"
                             targetProject=".\src\main\resources">
                <property name="enableSubPackages" value="true"/>
            </sqlMapGenerator>
            <!-- Mapper接口的生成策略 -->
            <javaClientGenerator type="XMLMAPPER"
                                 targetPackage="com.hhxy.mapper" targetProject=".\src\main\java">
                <property name="enableSubPackages" value="true"/>
            </javaClientGenerator>
            <!-- 逆向分析的表 -->
            <!-- tableName设置为*号,可以对应所有表,此时不写domainObjectName -->
            <!-- domainObjectName属性指定生成出来的实体类的类名 -->
            <table tableName="t_emp" domainObjectName="Emp"/>
            <table tableName="t_dept" domainObjectName="Dept"/>
        </context>
    </generatorConfiguration>
    
  • Step5 : Test

    Start the reverse engineering plugin:

    • method one:

      image-20220911194812501

    • Method 2 (need to download the Maven Help plugin):

      image-20220911194714454

The result is as follows:

image-20220911193138860

image-20220911200509171

Notice: The pojo class generated by reverse engineering does not help us rewrite toStringthe method, this needs to be rewritten manually

2. Detailed explanation of reverse engineering configuration file parameters

  • contextLabel : Contains all reverse engineering configuration information

    • id attribute, used to locate configuration information for reverse engineering
    • targetRuntime attribute: Set the version of the generated reverse engineering, two values
      • MyBatis3Simple : Generate basic CRUD (fresh and concise version), which generates five basic methods of adding, deleting, modifying and checking
      • MyBatis3 : Generate conditional CRUD (luxury premium version), generate all operations on a single table (including conditional SQL)
  • jdbcConnectionLabel: used to set the connection information of the database

  • propertyLabel : Set the relevant configuration information for generating reverse engineering

    • name attribute (associated value attribute):
      • javaFileEncoding: Used to set the encoding format for generating reverse engineering
      • suppressAllComments: set whether to automatically generate comments
      • enableDubPackages: Set whether to use subpackages
      • trimStrings: Set whether to remove the spaces before and after the fields in the table in the database (control the format of the attribute name generation of the pojo class), it is strongly recommended that the value be true
  • javaModelGeneratorTags: Build Settings for JavaBean Classes

    • targetPackage attribute: used to set the package name of the generated JavaBean
    • targetProject attribute: used to set the location where JavaBean is generated
  • sqlMapGeneratorTags: Set the generation strategy of the SQL mapping file

    • targetPackage attribute: used to set the file directory where the generated SQL mapping file is located
    • targetProject attribute: used to set the location of the generated SQL mapping file
  • JavaClientgeneratorLabel: Set the generation strategy of the Mapper interface

    • type attribute: Set the mapping method of XML and Mapper interface, the value XMLMAPPER indicates that the interface and XML are completely separated (strongly recommended)
    • targetPackage attribute: used to set the package where the generated Mapper is located
    • targetProject attribute: used to set the location where the Mapper interface is generated
  • tableLabel: used to set the class name of the entity class corresponding to the table name in the database (a table can be reverse engineered to generate a corresponding entity class, and this label is used to set the class name of the generated entity class)

    • tableName : table name
    • domainObjectName : entity class name

3. QBC query

  In the previous quick start, we used reverse engineering to generate a fresh and concise version of SQL, which has a single function and only adds, deletes, modifies, and checks five methods. If you want to use reverse engineering to generate more complex SQL, you need to targetRuntimeset the property to MyBatis3(Luxury Premium Edition), which contains all SQL for a single table

  QBC (Query By Criteria) refers to the conditional query by using the Criteria object

Compared with the fresh and concise version, the luxury premium version will generate two more classes:

image-20220911230416592

Luxury Premium EditionThere are four main methods in: normal method , selective method , conditional method and hybrid method

  • Normal method : normal method name, for example: insertupdate

  • Selective method : the method name generally Selectiveends with the following common ones: insertSelective(selective addition), updateSelective(selective modification)

  • Conditional method : The method name generally ends with Example, the common ones are: updateByPrimaryKey,updateByExample

  • Mixed methods : mainly a mixture of conditional methods and selective methods, such as: updateByPrimaryKeySelective,updateByExampleSelective

focus :

  • The difference between the normal method and the selective method : the selective method will not set the set to null to null, but adopt the default value of the field when it is set to null; while the normal method will directly set the field to null The value is set to null, regardless of its default value (mainly for modifying and adding two methods)
  • To query all methods, you only need to selectByExample()set the condition of the conditional query to null to query all, namely:selectByExample(null)

QBC Interlude Demonstration :

For the environment required for the demonstration, you can directly use the configuration in the quick start, but one thing is to change the mode generated by reverse engineering to the luxury premium version, and the rest are as usual

image-20220912131821182

import com.hhxy.mapper.EmpMapper;
import com.hhxy.pojo.Emp;
import com.hhxy.pojo.EmpExample;
import com.hhxy.utils.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;

import java.util.List;

/**
 * 逆向工程(奢华尊享版)测试类
 * @author ghp
 * @date 2022/9/12
 */
public class MBGTest {
    
    

    @Test
    public void MBGTest() {
    
    
        //1、获取SqlSessionFactory对象
        SqlSessionFactory sqlSF = SqlSessionFactoryUtil.getSqlSF();
        //2、获取SqlSession对象
        SqlSession sqlS = sqlSF.openSession();
        //3、获取Mapper接口对象
        EmpMapper mapper = sqlS.getMapper(EmpMapper.class);
        //4、执行SQL
        /*
        //1)根据Id进行查询
        Emp emp = mapper.selectByPrimaryKey(3);
        System.out.println(emp);
        //2)查询所有
        List<Emp> emps = mapper.selectByExample(null);
        emps.forEach(System.out::println);
        */

        //3)QBC查询,查询员工姓名是张三的
        //①获取Example对象
        EmpExample empExample = new EmpExample();
        //②获取条件对象Criteria
        EmpExample.Criteria criteria = empExample.createCriteria();
        //③设置条件

        String empName = "张三";
        //设置单条件(姓名为张三)
//        criteria.andEmpNameEqualTo(empName);

        //设置多条件
        //and连接词,通过链式编程实现(查询姓名为张三 并且 年龄在18~22之间):
//        criteria.andEmpNameEqualTo(empName).andAgeBetween(18,22);
        //or连接词(查询姓名为张三 或 李四)
        criteria.andEmpNameEqualTo("张三");
        empExample.or().andEmpNameEqualTo("李四");

        //④进行QBC查询
        List<Emp> emps = mapper.selectByExample(empExample);
        emps.forEach(System.out::println);
    }
}

Guess you like

Origin blog.csdn.net/qq_66345100/article/details/130113820