[Mybatis from entry to actual combat tutorial] Chapter 9 Mybatis Generator code generation

Nine, Mybatis Generator code generation

    Although MyBatis is a simple and easy-to-learn framework, configuring XML files is also a rather cumbersome process, and there will be many errors that are not easy to locate. When a large number of objects need to be generated during work, there is too much repetitive work, and life is simply hopeless.
    
    To this end, MyBatis Generator was officially developed. It only needs a small amount of simple configuration, and can complete a large number of table-to-Java object generation tasks. It has the advantages of zero error and high speed, freeing developers to focus more on business logic development.

9.1 Introduction to generated files

    The files generated by MyBatis Generator include three types:
        1. Model entity file, which generates a Model entity corresponding to a database table;
        2. Mapper interface file, where data operation methods are defined;
        3. Mapper XML configuration file;

9.2 Configuration dependencies

<dependencies>
    <!--引入mybatis的依赖-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
    </dependency>
    <!--  mysql -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.49</version>
    </dependency>
    <!-- log4j -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <!--mybatis代码生成器-->
    <dependency>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-core</artifactId>
        <version>1.3.7</version>
    </dependency>
</dependencies>

9.3 Import related configuration

    We only need to introduce log4j.properties instead of mybatis-config.xml.

9.4 Generate configuration file

generator.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>
    <!--
        context:生成一组对象的环境
        id:必选,上下文id,用于在生成错误时提示
        targetRuntime:
            1,MyBatis3:默认的值,生成基于MyBatis3.x以上版本的内容,包括XXXBySample;
            2,MyBatis3Simple:类似MyBatis3,只是不生成XXXBySample;
    -->
    <context id="testTables" targetRuntime="MyBatis3">
        <!-- 为模型生成序列化方法-->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
        <!-- 为生成的Java模型创建一个toString方法 -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
        <!--生成mapper.xml时覆盖原文件-->
        <plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" />

        <commentGenerator>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

        <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/ssm"
                        userId="root"
                        password="root">
        </jdbcConnection>

        <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
            NUMERIC 类型解析为java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!--
            Java模型创建器,是必须要的元素
            targetPackage:生成的类要放的包,真实的包受enableSubPackages属性控制;
            targetProject:目标项目,指定一个存在的目录下,生成的内容会放到指定目录中,如果目录不存在,MBG不会自动建目录
        -->
        <javaModelGenerator targetPackage="com.newcapec.entity" targetProject=".\src\main\java">
            <!--  for MyBatis3/MyBatis3Simple
                自动为每一个生成的类创建一个构造方法,构造方法包含了所有的field;而不是使用setter;
             -->
            <property name="constructorBased" value="true"/>

            <!-- 在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下 -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!--
            生成SQL map的XML文件生成器
            targetPackage/targetProject:同javaModelGenerator
        -->
        <sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>

        <!--
            对于mybatis来说,即生成Mapper接口,注意,如果没有配置该元素,那么默认不会生成Mapper接口
            targetPackage/targetProject:同javaModelGenerator
            type:选择怎么生成mapper接口(在MyBatis3/MyBatis3Simple下):
            1,ANNOTATEDMAPPER:会生成使用Mapper接口+Annotation的方式创建(SQL生成在annotation中),不会生成对应的XML;
            2,MIXEDMAPPER:使用混合配置,会生成Mapper接口,并适当添加合适的Annotation,但是XML会生成在XML中;
            3,XMLMAPPER:会生成Mapper接口,接口完全依赖XML;
        -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.newcapec.mapper" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>


        <!-- 选择一个table来生成相关文件,可以有一个或多个table,必须要有table元素
        选择的table会生成一下文件:
        1,SQL map文件
        2,生成一个主键类;
        3,除了BLOB和主键的其他字段的类;
        4,包含BLOB的类;
        5,一个用户生成动态查询的条件类(selectByExample, deleteByExample),可选;
        6,Mapper接口(可选)

        tableName(必要):要生成对象的表名;
        注意:大小写敏感问题。正常情况下,MBG会自动的去识别数据库标识符的大小写敏感度,在一般情况下,MBG会
            根据设置的schema,catalog或tablename去查询数据表,按照下面的流程:
            1,如果schema,catalog或tablename中有空格,那么设置的是什么格式,就精确的使用指定的大小写格式去查询;
            2,否则,如果数据库的标识符使用大写的,那么MBG自动把表名变成大写再查找;
            3,否则,如果数据库的标识符使用小写的,那么MBG自动把表名变成小写再查找;
            4,否则,使用指定的大小写格式查询;
        另外的,如果在创建表的时候,使用的""把数据库对象规定大小写,就算数据库标识符是使用的大写,在这种情况下也会使用给定的大小写来创建表名;
        这个时候,请设置delimitIdentifiers="true"即可保留大小写格式;

        可选:
        1,schema:数据库的schema;
        2,catalog:数据库的catalog;
        3,alias:为数据表设置的别名,如果设置了alias,那么生成的所有的SELECT SQL语句中,列名会变成:alias_actualColumnName
        4,domainObjectName:生成的domain类的名字,如果不设置,直接使用表名作为domain类的名字;可以设置为somepck.domainName,那么会自动把domainName类再放到somepck包里面;
        5,enableInsert(默认true):指定是否生成insert语句;
        6,enableSelectByPrimaryKey(默认true):指定是否生成按照主键查询对象的语句(就是getById或get);
        7,enableSelectByExample(默认true):MyBatis3Simple为false,指定是否生成动态查询语句;
        8,enableUpdateByPrimaryKey(默认true):指定是否生成按照主键修改对象的语句(即update);
        9,enableDeleteByPrimaryKey(默认true):指定是否生成按照主键删除对象的语句(即delete);
        10,enableDeleteByExample(默认true):MyBatis3Simple为false,指定是否生成动态删除语句;
        11,enableCountByExample(默认true):MyBatis3Simple为false,指定是否生成动态查询总条数语句(用于分页的总条数查询);
        12,enableUpdateByExample(默认true):MyBatis3Simple为false,指定是否生成动态修改语句(只修改对象中不为空的属性);
        13,modelType:参考context元素的defaultModelType,相当于覆盖;
        14,delimitIdentifiers:参考tableName的解释,注意,默认的delimitIdentifiers是双引号,如果类似MYSQL这样的数据库,使用的是`(反引号,那么还需要设置context的beginningDelimiter和endingDelimiter属性)
        15,delimitAllColumns:设置是否所有生成的SQL中的列名都使用标识符引起来。默认为false,delimitIdentifiers参考context的属性

        注意,table里面很多参数都是对javaModelGenerator,context等元素的默认属性的一个复写;
     -->
        <!--逆向工程不生成example类-->
        <!-- 列出要生成代码的所有表,这里配置的是不生成Example文件 -->
        <table tableName="users" domainObjectName="Users"
               enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               selectByExampleQueryId="false">
            <!-- 如果设置为true,生成的model类会直接使用column本身的名字,而不会再使用驼峰命名方法 -->
            <property name="useActualColumnNames" value="false"/>
        </table>
    </context>
</generatorConfiguration>

    Detailed explanation of the most complete configuration of Mybatis Generator:
        https://blog.csdn.net/qq_33326449/article/details/105930655

9.5 Generate file code

public class Generator {

    public static void main(String[] args) throws Exception {
        //是否覆盖已有文件
        boolean overwirte = true;
        DefaultShellCallback callback = new DefaultShellCallback(overwirte);
        List<String> warnings = new ArrayList<>();

        //创建配置解析类
        ConfigurationParser configurationParser = new ConfigurationParser(warnings);
        InputStream in = Generator.class.getClassLoader().getResourceAsStream("generator.xml");
        Configuration configuration = configurationParser.parseConfiguration(in);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(configuration, callback, warnings);
        myBatisGenerator.generate(null);
        System.out.println("代码生成成功...");
    }
}

9.6 Third-party plug-ins

9.6.1 Free Mybatis Tool

install plugin

    File -> Settings -> Plugins -> Search box input: Free Mybatis Tool, click Install to install.
    
    Note: After the installation is complete, it is best to restart IDEA.

Reverse generate mapper, class

    Through this plug-in, there is no need to use the official mybatis reverse generation package, write configuration files, etc., and only need to connect to the corresponding database to achieve reverse generation of corresponding classes, mapper files, etc.

Step 1: Connect to the database

 Step 2: Configure Driver (first use)

    Click Driver: Mysql -> Go to Driver to configure the MySQL driver;

Step 3: Find the table that needs to be reverse-generated and right-click to select Mybatis-Generator

Step 4: Configuration

jump function

    When using the mybatis framework, are you still looking for the location of the corresponding mapper or dao program by clicking on it class by class? That would be very cumbersome and a waste of time. And this Free Mybatis Tool plugin provides a jump function. You can jump to the corresponding place by clicking the arrow.

9.6.2 Easy Code

    EasyCode is a plug-in of idea, which can graphically generate entity, controller, service, dao, mapper... without any coding, simple and powerful.

install plugin

    File -> Settings -> Plugins -> Search box input: EasyCode, click Install to install.
    
    Note: After the installation is complete, it is best to restart IDEA.

Reverse generate mapper, class

    Find the table that needs to be reverse-generated and right-click to select EasyCode.
        1. Generate Code, code generation;
        2. Config Table, configuration table information;

Guess you like

Origin blog.csdn.net/ligonglanyuan/article/details/124442778