目录

mybatis代码生成器

概述

MyBatis Generator:简称MBG,是一个专门为MyBatis框架使用者定制的代码生成器,可以快速的根据表生成对应的映射文件,接口,以及bean类。支持基本的增删改查,以及QBC风格的条件查询。但是表连接、存储过程等这些复杂sql的定义需要我们手工编写

官方文档地址

官方工程地址

注意
mybatis generator支持多种方式生成代码,本篇文章描述使用maven插件生成代码。

添加依赖和插件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!--
mybatis-generator是一款在使用mybatis框架时,自动生成model,dao和mapper的工具,
很大程度上减少了业务开发人员的手动编码时间
-->
<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.3.7</version>
</dependency>

<build>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.4.0</version>
                <configuration>
                    <!-- mybatis用于生成代码的配置文件 -->
                    <configurationFile>src/main/resources/generatorConfig.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>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>${mysql-connector-java.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

编写generatorConfig.xml

generatorConfig.xml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?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>

    <properties resource="./db.properties"/>
    <!--
      targetRuntime="MyBatis3Simple":生成简单版的CRUD
      "MyBatis3":豪华版
    -->
    <context id="DB2Tables" targetRuntime="MyBatis3">

      	<!--
        https://www.cnblogs.com/xxoome/p/10068780.html
        当你取消了所有注释,你在重复运行generator时在mapper.xml中会出现重复的元素。并且这个plugin可以解决这个问题
        -->
        <!--覆盖生成XML文件-->
        <plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" />
      
        <!-- 忽略生成注释日期 -->
        <commentGenerator>
            <!-- 这个元素用来去除指定生成的注释中是否包含生成的日期 false:表示保护 -->
            <!-- 如果生成日期,会造成即使修改一个字段,整个实体类所有属性都会发生变化,不利于版本控制,所以设置为true -->
            <property name="suppressDate" value="true" />
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>


        <!-- jdbcConnection:指定如何连接到目标数据库 -->
        <jdbcConnection driverClass="${driver}"
                        connectionURL="${url}"
                        userId="${username}"
                        password="${password}">
            <!--
             解决问题:Cannot obtain primary key information from the database, generated objects may be incomplete
            -->
            <property name="nullCatalogMeansCurrent" value="true"/>
        </jdbcConnection>

        <!--  -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 生成model实体类文件位置 -->
        <javaModelGenerator targetPackage="com.eh.eden.ssm.orm.bean"
                            targetProject="/Users/david/my/study/project/eden/ssm/src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- 生成mapper.xml配置文件位置 -->
        <sqlMapGenerator targetPackage="mybatis.mapper"
                         targetProject="/Users/david/my/study/project/eden/ssm/src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!-- 生成mapper接口文件位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.eh.eden.ssm.orm.dao"
                             targetProject="/Users/david/my/study/project/eden/ssm/src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!-- 需要生成的实体类对应的表名,多个实体类复制多份该配置即可 -->
        <!--
        Example设置为true会生成QBC风格的代码
        QBC(Query By Criteria) API提供了检索对象的另一种方式,它主要由Criteria接口、Criterion接口和Expression类组成,
        它支持在运行时动态生成查询语句。
        建议关闭,所有的sql都应由开发自己来统一维护,虽然会降低开发速度,但是集中管理可以提高可阅读星,出现问题也能快速定位sql
        -->
        <table tableName="tbl_dept" domainObjectName="Dept"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
        </table>
    </context>
</generatorConfiguration>

运行插件

1
$ mvn mybatis-generator:generate

运行结果

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$ mvn mybatis-generator:generate
[INFO] Scanning for projects...
[WARNING] Failed to build parent project for com.eh:ssm:war:1.0-SNAPSHOT
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] Building ssm Maven Webapp 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- mybatis-generator-maven-plugin:1.4.0:generate (default-cli) @ ssm ---
[INFO] Connecting to the Database
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Sat Oct 10 17:19:27 CST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
[INFO] Introspecting table tbl_dept
[INFO] Generating Record class for table tbl_dept
[INFO] Generating Mapper Interface for table tbl_dept
[INFO] Generating SQL Map for table tbl_dept
[INFO] Saving file DeptMapper.xml
[INFO] Saving file Dept.java
[INFO] Saving file DeptMapper.java
[WARNING] Existing file /Users/david/my/study/project/eden/ssm/src/main/java/com/eh/eden/ssm/orm/bean/Dept.java was overwritten
[WARNING] Existing file /Users/david/my/study/project/eden/ssm/src/main/java/com/eh/eden/ssm/orm/dao/DeptMapper.java was overwritten
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.064 s
[INFO] Finished at: 2020-10-10T17:19:28+08:00
[INFO] Final Memory: 15M/194M
[INFO] ------------------------------------------------------------------------

测试

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package com.eh.eden.ssm.orm.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
import org.testng.annotations.Test;

@ContextConfiguration({"classpath:/application.xml"})
public class DeptMapperTest extends AbstractTransactionalTestNGSpringContextTests {

    @Autowired
    private DeptMapper deptMapper;

    @Test
    public void test() {
        System.out.println(deptMapper.selectByPrimaryKey(1).getDeptName());
    }

}

测试结果:

1
2
3
4
5
6
7
8
20201010 17:24:46 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Creating a new SqlSession
20201010 17:24:46 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1c3146bc]
20201010 17:24:46 [main] DEBUG o.m.spring.transaction.SpringManagedTransaction - JDBC Connection [com.mchange.v2.c3p0.impl.NewProxyConnection@555cf22 [wrapping: com.mysql.cj.jdbc.ConnectionImpl@6bb2d00b]] will be managed by Spring
20201010 17:24:46 [main] DEBUG c.e.eden.ssm.orm.dao.DeptMapper.selectByPrimaryKey - ==>  Preparing: select id, dept_name from tbl_dept where id = ?
20201010 17:24:46 [main] DEBUG c.e.eden.ssm.orm.dao.DeptMapper.selectByPrimaryKey - ==> Parameters: 1(Integer)
20201010 17:24:46 [main] DEBUG c.e.eden.ssm.orm.dao.DeptMapper.selectByPrimaryKey - <==      Total: 1
20201010 17:24:46 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1c3146bc]
开发部