想快速開始,請直接拉到最後,看整體配置。
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"/>
複製程式碼
配置檔案中的內容如下

配置context
注意是配置在 <generatorConfiguration>
下
<context id="myContext" targetRuntime="MyBatis3" defaultModelType="flat">
</context>
複製程式碼
- id : 隨便填,保證多個 context id 不重複就行
- defaultModelType : 可以不填,預設值 conditional,flat表示一張表對應一個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 對配置的循序還有要求)
- property (0..N)
- plugin (0..N)
- commentGenerator (0 or 1)
- jdbcConnection (需要connectionFactory 或 jdbcConnection)
- javaTypeResolver (0 or 1)
- javaModelGenerator (至少1個)
- sqlMapGenerator (0 or 1)
- javaClientGenerator (0 or 1)
- table (1..N)
plugin
配置一個外掛,例如
<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
複製程式碼
這個外掛給生成的Java模型物件增加了equals和hashCode方法
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
的檔案,如下

當 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 執行
