想快速开始,请直接拉到最后,看整体配置。

MyBatis Generator 是 MyBatis 提供的一个代码生成工具。可以帮我们生成 表对应的持久化对象(po)、操作数据库的接口(dao)、CRUD sql的xml(mapper)。

MyBatis Generator 是一个独立工具,你可以下载它的jar包来运行、也可以在 Ant 和 maven 运行。

使用环境

我是在 maven 中配置并使用的。这篇文章也是基于 maven 环境来讲解。

既然使用了 MyBatis Generator ,那么你的项目一定使用了 MyBatis, 并且一定使用了某一种数据库,并且这些依赖应该已经在 maven 中配置好了。

例如

接下来需要在 pom 中引入 MyBatis Generator 插件

引入 MyBatis Generator 插件

在 pom 的根节点下添加以下配置

<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
</plugin>
<plugins>
</build>
复制代码

配置 MyBatis Generator 插件

光引入 MyBatis Generator 插件还不行,还得配置 MyBatis Generator插件

配置 MyBatis Generator config 文件路径

MyBatis Generator 插件需要根据一个 MyBatis Generator config 文件,来具体运行

配置如下,版本我用的是目前最新的版本 1.3.7

<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<configuration>
<!--mybatis的代码生成器的配置文件-->
<configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile>
</configuration>
</plugin>
<plugins>
</build>
复制代码

注意,这个路径是你的配置文件相对于该 pom 文件的路径

至于这个文件该怎么配置我们待会在

允许覆盖生成的文件

有时候我们的数据库表添加了新字段,需要重新生成对应的文件。常规做法是手动删除旧文件,然后在用 MyBatis Generator 生成新文件。当然你也可以选择让 MyBatis Generator 覆盖旧文件,省下手动删除的步骤。

配置如下

<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<configuration>
<!--mybatis的代码生成器的配置文件-->
<configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile>
<!--允许覆盖生成的文件-->
<overwrite>true</overwrite>
</configuration>
</plugin>
<plugins>
</build>
复制代码

值得注意的是,MyBatis Generator 只会覆盖旧的 po、dao、而 *mapper.xml 不会覆盖,而是追加,这样做的目的是防止用户自己写的 sql 语句一不小心都被 MyBatis Generator 给覆盖了

添加数据库驱动依赖

MyBatis Generator 需要链接数据库,肯定是需要对应数据库驱动的依赖的。

如下,给 MyBatis Generator 添加数据库驱动依赖

<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<configuration>
<!--mybatis的代码生成器的配置文件-->
<configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile>
<!--允许覆盖生成的文件-->
<overwrite>true</overwrite>
</configuration>
<dependencies>
<!-- mysql的JDBC驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
</dependencies>
</plugin>
<plugins>
</build>
复制代码

我用的数据库是 mysql ,其他数据库同理。注意数据库驱动的版本号,不同的版本对应的 MyBatis Generator 配置有些许不同,之后会讲。

大部分情况下,我们的项目中已经配置过了对应数据库的JDBC驱动,如下

现在在插件中又配置一次,感觉有些冗余,maven 提供了 includeCompileDependencies 属性,让我们在插件中引用 dependencies 的依赖,这样就不需要重复配置了。

配置如下

<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<configuration>
<!--mybatis的代码生成器的配置文件-->
<configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile>
<!--允许覆盖生成的文件-->
<overwrite>true</overwrite>
<!--将当前pom的依赖项添加到生成器的类路径中-->
<includeCompileDependencies>true</includeCompileDependencies>
</configuration>
</plugin>
<plugins>
</build>
复制代码

添加其他依赖

一般配置了 includeCompileDependencies 后就不需要配置其他依赖了,因为 includeCompileDependencies 会将当前 pom 的 dependencies 中所以 Compile 期的依赖全部添加到生成器的类路径中。

但有的人不想配置 includeCompileDependencies ,或者想在MyBatis Generator插件中使用另一个版本的依赖,就可以配置 dependencies

如图

另外,我看到网上大部分文章都会配置 mybatis-generator-core 这个依赖,但是 MyBatis Generator 官网的案例中都没有提到说要配置这个依赖,我没有配置,并且可以正常使用 MyBatis Generator

配置 MyBatis Generator Config

MyBatis Generator 插件启动后,会根据你在 pom 中配置都路径找到该配置文件。

这个配置文件才是详细都配置 MyBatis Generator 生成代码的各种细节。

其中最重要的就是 context ,你的配置文件至少得包含一个context

引入外部配置文件

MyBatis Generator config 是可以引入外部配置文件的,如下,路径为相对于当前配置文件的路径

代码如下,注意是配置在 <generatorConfiguration> 下

<!-- 引入配置文件 -->
<properties resource="application-dev.properties"/>
复制代码

配置文件中的内容如下

之后可以通过 ${xxx} 来引用外部配置文件中的值

配置context

注意是配置在 <generatorConfiguration> 下

<context id="myContext" targetRuntime="MyBatis3" defaultModelType="flat">

</context>
复制代码
  • id : 随便填,保证多个 context id 不重复就行
  • defaultModelType : 可以不填,默认值 conditionalflat表示一张表对应一个po
  • targetRuntime :可以不填,默认值 MyBatis3,常用的还有 MyBatis3Simple,这个配置会影响生成的 dao 和 mapper.xml的内容

targetRuntime = MyBatis3,生成的 dao 和 mapper.xml 如下

targetRuntime = MyBatis3Simple,生成的 dao 和 mapper.xml 如下,接口会少很多,只包含最最常用的

context 节点就讲完了,唯一需要注意的就是targetRuntime的值,该配置成什么看个人喜好

context的子元素

上一节只是配置了 context 节点, context 里面还有子元素需要配置。

context的子元素必须按照以下给出的个数、顺序配置。(是的,没错 MyBatis Generator 对配置的循序还有要求)

  1. property (0..N)
  2. plugin (0..N)
  3. commentGenerator (0 or 1)
  4. jdbcConnection (需要connectionFactory 或 jdbcConnection)
  5. javaTypeResolver (0 or 1)
  6. javaModelGenerator (至少1个)
  7. sqlMapGenerator (0 or 1)
  8. javaClientGenerator (0 or 1)
  9. table (1..N)

plugin

配置一个插件,例如

<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
复制代码

这个插件给生成的Java模型对象增加了equals和hashCode方法

commentGenerator

commentGenerator 用来配置生成的注释。默认是生成注释的,并且会生成时间戳,如下

如果你想要保留注释和时间戳,可以不配置 commentGenerator

如果你不想保留时间戳,需要如下配置

<commentGenerator>
<!-- 不希望生成的注释中包含时间戳 -->
<property name="suppressDate" value="true"/>
</commentGenerator>
复制代码

默认生成的注释是不会有 db 表中字段的注释,如果你想知道每个字段在数据库中的含义(前提是数据库中对应表的字段你添加了注释),可以如下配置

<commentGenerator>
<!-- 添加 db 表中字段的注释 -->
<property name="addRemarkComments" value="true"/>
</commentGenerator>
复制代码

但说实话,MyBatis Generator 生成注释无用信息太多了,所以我一般都选择不生成注释

<commentGenerator>
<!-- 是否不生成注释 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
复制代码

jdbcConnection

MyBatis Generator 需要链接数据库,所以需要配置 jdbcConnection,具体如下

<jdbcConnection driverClass="${spring.datasource.driverClassName}"
connectionURL="${spring.datasource.url}"
userId="${spring.datasource.username}"
password="${spring.datasource.password}">
<!--高版本的 mysql-connector-java 需要设置 nullCatalogMeansCurrent=true-->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
复制代码

${}里面是外部配置文件中的"name"

你也可以写死,那就不需要配置<properties resource="application-dev.properties"/>

这里面值得注意的是<property name="nullCatalogMeansCurrent" value="true"/>,因为我用的 mysql-connector-java 版本是 8.0.17,如果配置这一项,会找不到对应的数据库,官网对此的解释是

具体原因参考这篇文章 MyBatis Generator踩坑与自救

javaTypeResolver

javaTypeResolver 是配置 JDBC 与 java 的类型转换规则,或者你也可以不用配置,使用它默认的转换规则。

就算配置也只能配置 bigDecimal 类型和时间类型的转换

<javaTypeResolver>
<!--是否使用 bigDecimal,默认false。
false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer
true,把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal-->
<property name="forceBigDecimals" value="true"/>
<!--默认false
false,将所有 JDBC 的时间类型解析为 java.util.Date
true,将 JDBC 的时间类型按如下规则解析
DATE -> java.time.LocalDate
TIME -> java.time.LocalTime
TIMESTAMP -> java.time.LocalDateTime
TIME_WITH_TIMEZONE -> java.time.OffsetTime
TIMESTAMP_WITH_TIMEZONE -> java.time.OffsetDateTime
-->
<property name="useJSR310Types" value="true"/>
</javaTypeResolver>
复制代码

javaModelGenerator

配置 po 生成的包路径和项目路径,如下

<javaModelGenerator targetPackage="com.wqlm.boot.user.po" targetProject="src/main/java">
<!-- 是否让schema作为包的后缀,默认为false -->
<!--<property name="enableSubPackages" value="false"/>-->
<!-- 是否针对string类型的字段在set方法中进行修剪,默认false -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
复制代码

<property name="trimStrings" value="true"/> 生成出来的 set 方法如下

<property name="enableSubPackages" value="true"/> 时,可能会在 po 目录下在创建一个 “数据库名” 的文件夹,生成的 po 会放在该文件夹下,也就是说会多一层目录,用的上的可以配置

sqlMapGenerator

配置 Mapper.xml 文件的生成目录

<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<!--<property name="enableSubPackages" value="false"/>-->
</sqlMapGenerator>
复制代码

javaClientGenerator

配置 XxxMapper.java 文件的生成目录

<javaClientGenerator targetPackage="com.wqlm.boot.user.dao" targetProject="src/main/java" type="XMLMAPPER">
<!--<property name="enableSubPackages" value="false"/>-->
</javaClientGenerator>
复制代码

type="XMLMAPPER" 会将接口的实现放在 mapper.xml中,也推荐这样配置。也可以设置 type 为其他值,比如 type="ANNOTATEDMAPPER",接口的实现通过注解写在接口上面,如图

如果采用这种方式,不会生成 mapper.xml 也不用配置 <sqlMapGenerator>,但是采用注解来实现接口应对简单查询还好,如果是复杂查询并不如xml方便,所以还是建议将type配置成XMLMAPPER

table

一个 table 对应一张表,如果想同时生成多张表,需要配置多个 table

<!-- schema为数据库名,oracle需要配置,mysql不需要配置。
tableName为对应的数据库表名
domainObjectName 是要生成的实体类名(可以不指定)
enableXXXByExample 默认为 true, 为 true 会生成一个对应Example帮助类,帮助你进行条件查询,不想要可以设为false
-->
<table schema="" tableName="user" domainObjectName="User"
enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
enableUpdateByExample="false" selectByExampleQueryId="false">
<!--是否使用实际列名,默认为false-->
<!--<property name="useActualColumnNames" value="false" />-->
</table>
复制代码

其中 domainObjectName 不配置时,它会按照帕斯卡命名法将表名转换成类名

enableXXXByExample 默认为true,但只有在targetRuntime="MyBatis3"时才生效

生效时,会在po下多生成一个 XxxExample.java 的文件,如下

一个简单的user的Example帮助类有470行,我一般不会去用,如上全设置为false

当 targetRuntime="MyBatis3Simple"时,enableXXXByExample 不管为true、还是false 都不生效

整体配置

pom 整体配置

<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<configuration>
<!--mybatis的代码生成器的配置文件-->
<configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile>
<!--允许覆盖生成的文件-->
<overwrite>true</overwrite>
<!--将当前pom的依赖项添加到生成器的类路径中-->
<!--<includeCompileDependencies>true</includeCompileDependencies>-->
</configuration>
<dependencies>
<!--mybatis-generator插件的依赖包-->
<!--<dependency>-->
<!--<groupId>org.mybatis.generator</groupId>-->
<!--<artifactId>mybatis-generator-core</artifactId>-->
<!--<version>1.3.7</version>-->
<!--</dependency>-->
<!-- mysql的JDBC驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
</dependencies>
</plugin>
</plugins>
<build>
复制代码

MyBatis Generator Config 整体配置

<?xml version="1.0" encoding="UTF-8" ?>
<!--mybatis的代码生成器相关配置-->
<!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="application-dev.properties"/> <!-- 一个数据库一个context,context的子元素必须按照它给出的顺序
property*,plugin*,commentGenerator?,jdbcConnection,javaTypeResolver?,
javaModelGenerator,sqlMapGenerator?,javaClientGenerator?,table+
-->
<context id="myContext" targetRuntime="MyBatis3" defaultModelType="flat"> <!-- 这个插件给生成的Java模型对象增加了equals和hashCode方法 -->
<!--<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>--> <!-- 注释 -->
<commentGenerator>
<!-- 是否不生成注释 -->
<property name="suppressAllComments" value="true"/>
<!-- 不希望生成的注释中包含时间戳 -->
<!--<property name="suppressDate" value="true"/>-->
<!-- 添加 db 表中字段的注释,只有suppressAllComments为false时才生效-->
<!--<property name="addRemarkComments" value="true"/>-->
</commentGenerator> <!-- jdbc连接 -->
<jdbcConnection driverClass="${spring.datasource.driverClassName}"
connectionURL="${spring.datasource.url}"
userId="${spring.datasource.username}"
password="${spring.datasource.password}">
<!--高版本的 mysql-connector-java 需要设置 nullCatalogMeansCurrent=true-->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection> <!-- 类型转换 -->
<javaTypeResolver>
<!--是否使用bigDecimal,默认false。
false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer
true,把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal-->
<property name="forceBigDecimals" value="true"/>
<!--默认false
false,将所有 JDBC 的时间类型解析为 java.util.Date
true,将 JDBC 的时间类型按如下规则解析
DATE -> java.time.LocalDate
TIME -> java.time.LocalTime
TIMESTAMP -> java.time.LocalDateTime
TIME_WITH_TIMEZONE -> java.time.OffsetTime
TIMESTAMP_WITH_TIMEZONE -> java.time.OffsetDateTime
-->
<!--<property name="useJSR310Types" value="false"/>-->
</javaTypeResolver> <!-- 生成实体类地址 -->
<javaModelGenerator targetPackage="com.wqlm.boot.user.po" targetProject="src/main/java">
<!-- 是否让 schema 作为包的后缀,默认为false -->
<!--<property name="enableSubPackages" value="false"/>-->
<!-- 是否针对string类型的字段在set方法中进行修剪,默认false -->
<property name="trimStrings" value="true"/>
</javaModelGenerator> <!-- 生成Mapper.xml文件 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<!--<property name="enableSubPackages" value="false"/>-->
</sqlMapGenerator> <!-- 生成 XxxMapper.java 接口-->
<javaClientGenerator targetPackage="com.wqlm.boot.user.dao" targetProject="src/main/java" type="XMLMAPPER">
<!--<property name="enableSubPackages" value="false"/>-->
</javaClientGenerator> <!-- schema为数据库名,oracle需要配置,mysql不需要配置。
tableName为对应的数据库表名
domainObjectName 是要生成的实体类名(可以不指定,默认按帕斯卡命名法将表名转换成类名)
enableXXXByExample 默认为 true, 为 true 会生成一个对应Example帮助类,帮助你进行条件查询,不想要可以设为false
-->
<table schema="" tableName="user" domainObjectName="User"
enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
enableUpdateByExample="false" selectByExampleQueryId="false">
<!--是否使用实际列名,默认为false-->
<!--<property name="useActualColumnNames" value="false" />-->
</table>
</context>
</generatorConfiguration>
复制代码

外部配置文件整体配置

MyBatis Generator Config 引用的外部配置文件内容如下

# mysql
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/boot?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
复制代码

使用 MyBatis Generator

配置好后,双击 maven 中的 MyBatis Generator 运行

MyBatis Generator 超详细配置的更多相关文章

  1. [转载]Mybatis Generator最完整配置详解

    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration ...

  2. MyBatis Generator generatorConfig.xml配置详解

    所有Generator的xml详细说明见:http://mybatis.org/generator/configreference/xmlconfig.html (英文版) 引用 http://blo ...

  3. Mybatis Generator配置文件完整配置详解

    完整的Mybatis Generator(简称MBG)的最完整配置文件,带详解,再也不用去看EN的User Guide了 可以搭配着mybatis generator的中文文档看:http://mbg ...

  4. 【转】Mybatis Generator最完整配置详解

    本文转简书:http://www.jianshu.com/p/e09d2370b796 --> --> <!-- 自动识别数据库关键字,默认false,如果设置为true,根据Sql ...

  5. Mybatis Generator最完整配置详解

    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration ...

  6. mybatis逆向工程generatorConfiguration详细配置

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguratio ...

  7. Mybatis Generator xml格式配置

    Mybatis Generator可以使用Maven方式和Java方法,使用Maven这里是配置文件: <?xml version="1.0" encoding=" ...

  8. Mybatis Generator 最完整配置详解

    这是从CSDN找到的一篇翻译文章,尝试重新排版后转载. 1. < generatorConfiguration > 标签 1.1 可以用于加载配置项或者配置文件,在整个配置文件中就可以使用 ...

  9. 【转】Android-Universal-Image-Loader 图片异步加载类库的使用(超详细配置)

    Android-Universal-Image-Loader 原文地址:http://blog.csdn.net/vipzjyno1/article/details/23206387 这个图片异步加载 ...

随机推荐

  1. Wannafly Camp 2020 Day 2D 卡拉巴什的字符串 - 后缀自动机

    动态维护任意两个后缀的lcp集合的mex,支持在串末尾追加字符. Solution 考虑在 SAM 上求两个后缀的 LCP 的过程,无非就是找它们在 fail 树上的 LCA,那么 LCP 长度就是这 ...

  2. C#依赖注入 简体demo

      class Program { static void Main(string[] args) { Dal dal = new MySql(); dal.Add(); Dal dal1 = new ...

  3. Quick Sort(快速排序)

    Quick Sort Let's arrange a deck of cards. Your task is to sort totally n cards. A card consists of a ...

  4. 《NVM-Express-1_4-2019.06.10-Ratified》学习笔记(8.7)Standard Vendor Specific Command Format

    8.7 Standard Vendor Specific Command Format 标准的厂商特定命令格式 Controller可以支持Figure 106中定义的标准的Vendor Specif ...

  5. [Arc083D/At3535] Restoring Road Network - 最短路,结论

    [Arc083D/At3535] 有 \(N\) 个城市,城市与城市之间用长度为整数的无向道路连接. 现有一考古学家找到了一张 \(N×N\) 的表 \(A\) ,这张表代表了这 \(N\) 座城市两 ...

  6. Linux下搭建PHP环境的参考文章小记

    之前也在Linux上安装过两次,但是当我再次需要安装时,还是很多不懂的地方,于是记下此篇,以防下次再费经心思找到不合适的文章,瞎折腾. 通过参考这几篇文章,成功的安装好了自己的PHP(LNMP)环境. ...

  7. ReviewBoard使用:添加SVN

    1.登录ReviewBoard,选择“Admin” 2.选择 “Repositores”,点击按钮“Add” 3.填写内容,然后点击按钮“SAVE”保存 Name:仓库名称(自己随意写) Hostin ...

  8. set的使用

    集合是Python的一种数据类型,集合是一个可变容器.常用于列表的去重. 什么是集合 集合是一个可变容器 集合中的数据对象都是唯一的(不可重复) 集合是无序的存储结构 集合是可迭代对象 集合内的元素是 ...

  9. C语言 malloc函数

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.                                                 ...

  10. 2020算法设计竞赛 C 汉诺塔

    作者:珩月链接:https://ac.nowcoder.com/discuss/367149来源:牛客网 将木板按照Xi从小到大排序,将这时的Yi数列记为Zi数列,则问题变成将Zi划分为尽可能少的若干 ...