MyBatis Generator配置生成接口和XML映射文件的實(shí)現(xiàn)
在使用 MyBatis 進(jìn)行項(xiàng)目開(kāi)發(fā)時(shí),MyBatis Generator(MBG)是一個(gè)非常實(shí)用的工具,它能夠根據(jù)數(shù)據(jù)庫(kù)表結(jié)構(gòu)自動(dòng)生成實(shí)體類、Mapper 接口以及 XML 映射文件,大大提高了開(kāi)發(fā)效率。本文將詳細(xì)介紹如何配置 MyBatis Generator 以生成接口和 XML 映射文件,并對(duì)不同的 targetRuntime 風(fēng)格進(jìn)行介紹和推薦。
一、環(huán)境準(zhǔn)備
在開(kāi)始之前,確保你的項(xiàng)目中已經(jīng)添加了 MyBatis Generator 的相關(guān)依賴。如果你使用的是 Maven 項(xiàng)目,可以在 pom.xml 文件中添加如下依賴:
<dependencies>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- MyBatis Generator 插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>二、配置文件詳解
在 src/main/resources 目錄下創(chuàng)建 generatorConfig.xml 配置文件,以下是詳細(xì)的配置內(nèi)容及注釋:
<?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>
<!-- 配置上下文,id 唯一標(biāo)識(shí),targetRuntime 指定生成代碼的方式,風(fēng)格 MyBatis3DynamicSql,MyBatis3,MyBatis3Simple,MyBatis3Kotlin -->
<context id="mysqlTables" targetRuntime="MyBatis3" defaultModelType="flat">
<!-- 自動(dòng)檢查關(guān)鍵字,為關(guān)鍵字增加反引號(hào),如:`type` -->
<property name="autoDelimitKeywords" value="true"/>
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<!-- 指定生成的 Java 文件編碼 -->
<property name="javaFileEncoding" value="UTF-8"/>
<!-- 對(duì)生成的注釋進(jìn)行控制 -->
<commentGenerator>
<!-- 由于此插件生成的注釋不太美觀,這里設(shè)置不生成任何注釋 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!-- 數(shù)據(jù)庫(kù)鏈接 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://127.0.0.1:3306/your_database"
userId="your_username"
password="your_password">
<!-- 解決多個(gè)重名的表生成表結(jié)構(gòu)不一致問(wèn)題 -->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<!-- 不強(qiáng)制將所有的數(shù)值類型映射為 Java 的 BigDecimal 類型 -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 配置生成實(shí)體類的位置和包名 -->
<javaModelGenerator targetPackage="com.example.model" targetProject="src/main/java"/>
<!-- 配置生成 XML 映射文件的位置和包名 -->
<sqlMapGenerator targetPackage="com.example.mapper" targetProject="src/main/resources"/>
<!-- 配置生成 Mapper 接口的位置和包名,type="XMLMAPPER" 表示生成 XML 映射文件 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mapper" targetProject="src/main/java"/>
<!-- 配置要生成代碼的表,tableName 指定數(shù)據(jù)庫(kù)中的表名,domainObjectName 指定生成的實(shí)體類名 -->
<!-- 要生成對(duì)應(yīng)表配置,若想要生成全部表 使用 tableName="%" 即可 -->
<!-- 訂單詳情表 -->
<table tableName="order_detail" domainObjectName="OrderDetail"
<!-- 不生成Example -->
enableCountByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
enableUpdateByExample="false">
<!-- 自增主鍵列 -->
<generatedKey column="id" sqlStatement="MYSQL" identity="true"/>
<!-- 根據(jù)實(shí)際需求添加其他列的映射配置 -->
</table>
</context>
</generatorConfiguration>三、生成代碼
在項(xiàng)目根目錄下打開(kāi)終端,運(yùn)行以下命令生成代碼:
mvn mybatis-generator:generate
或者點(diǎn)擊 mybatis-generator 組件

運(yùn)行命令后,MyBatis Generator 會(huì)根據(jù) generatorConfig.xml 配置文件生成 Mapper 接口和對(duì)應(yīng)的 XML 映射文件。
四、不同 targetRuntime 風(fēng)格介紹和推薦
1. MyBatis3
描述:生成兼容 MyBatis 3.x 的代碼。這是最常用的目標(biāo),支持 MyBatis 的基礎(chǔ)功能,生成 Example 類、SQL 語(yǔ)句和常規(guī)的 Mapper 接口。
使用場(chǎng)景:當(dāng)使用 MyBatis 3.x 時(shí),這是最常見(jiàn)的選擇。
推薦:如果你的項(xiàng)目需要使用 MyBatis 3.x 的所有功能,包括復(fù)雜的查詢和條件類,選擇
MyBatis3風(fēng)格是一個(gè)不錯(cuò)的選擇。
2. MyBatis3Simple
描述:生成更加簡(jiǎn)化的代碼,省略了 Example 類和其他復(fù)雜功能。
使用場(chǎng)景:當(dāng)項(xiàng)目不需要復(fù)雜查詢或額外的功能時(shí),可以選擇該選項(xiàng),以減少生成的代碼量。
推薦:如果你的項(xiàng)目只需要基本的 CRUD 操作,不需要復(fù)雜的查詢條件,選擇
MyBatis3Simple風(fēng)格可以減少生成的代碼量,使項(xiàng)目更加簡(jiǎn)潔。
3. MyBatis3DynamicSql
描述:生成使用 MyBatis3 風(fēng)格的動(dòng)態(tài) SQL 的代碼。該選項(xiàng)支持通過(guò) MyBatis 提供的動(dòng)態(tài) SQL 功能(如 Example 類、Criteria 和動(dòng)態(tài) SQL 構(gòu)建器)生成更加靈活和復(fù)雜的 SQL 查詢。
使用場(chǎng)景:如果你需要?jiǎng)討B(tài)生成復(fù)雜的 SQL 語(yǔ)句,并使用 MyBatis 3.x 的動(dòng)態(tài) SQL 構(gòu)建功能,選擇該選項(xiàng)。
推薦:官方推薦使用
MyBatis3DynamicSql風(fēng)格,因?yàn)樗峁┝烁叩撵`活性和更強(qiáng)大的動(dòng)態(tài) SQL 支持,使用 Lambda 表達(dá)式可以避免條件對(duì)象滲透到上一層,代碼更加簡(jiǎn)潔和易于維護(hù)。
4. MyBatis3Kotlin
描述:生成 Kotlin 代碼。
使用場(chǎng)景:如果你的項(xiàng)目使用 Kotlin 語(yǔ)言,可以選擇該選項(xiàng)。
推薦:如果你的項(xiàng)目是基于 Kotlin 開(kāi)發(fā)的,選擇
MyBatis3Kotlin風(fēng)格可以生成與 Kotlin 語(yǔ)言兼容的代碼,利用 Kotlin 的語(yǔ)言特性,使代碼更加簡(jiǎn)潔和高效。
五、生成的 Example 類及解決辦法
1. 生成的 Example 類
當(dāng)使用 MyBatis3 風(fēng)格時(shí),MyBatis Generator 會(huì)生成 Example 類,這些類用于構(gòu)建復(fù)雜的查詢條件。例如,生成的 UserExample 類可能如下所示:
package com.example.model;
import java.util.ArrayList;
import java.util.List;
public class UserExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public UserExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
// 其他條件方法...
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}2. 問(wèn)題及解決辦法
問(wèn)題 1:Example 類過(guò)于復(fù)雜,導(dǎo)致代碼冗余
解決辦法:
使用
MyBatis3Simple風(fēng)格:如果你的項(xiàng)目不需要復(fù)雜的查詢條件,可以選擇MyBatis3Simple風(fēng)格,這樣可以避免生成 Example 類,減少代碼冗余。自定義生成策略:如果你仍然需要使用
MyBatis3風(fēng)格,但希望減少 Example 類的復(fù)雜性,可以通過(guò)自定義生成策略來(lái)簡(jiǎn)化 Example 類。例如,可以修改generatorConfig.xml文件中的<commentGenerator>配置,減少生成的注釋和不必要的代碼。
問(wèn)題 2:Example 類的使用導(dǎo)致代碼可讀性差
解決辦法:
使用 Lambda 表達(dá)式:在
MyBatis3DynamicSql風(fēng)格中,可以使用 Lambda 表達(dá)式來(lái)構(gòu)建查詢條件,使代碼更加簡(jiǎn)潔和易于理解。例如:
List<User> users = userMapper.selectMany(SelectStatementProvider.builder()
.select(UserDynamicSqlSupport.id, UserDynamicSqlSupport.name, UserDynamicSqlSupport.email)
.from(UserDynamicSqlSupport.user)
.where(UserDynamicSqlSupport.name, isEqualTo("張三"))
.build());封裝查詢條件:可以封裝查詢條件的構(gòu)建邏輯,使代碼更加模塊化和易于維護(hù)。例如,可以創(chuàng)建一個(gè)查詢條件構(gòu)建器類,將復(fù)雜的查詢條件封裝起來(lái):
public class UserQuery {
private UserExample example;
public UserQuery() {
this.example = new UserExample();
}
public UserQuery idIsNull() {
example.createCriteria().andIdIsNull();
return this;
}
public UserQuery idIsNotNull() {
example.createCriteria().andIdIsNotNull();
return this;
}
public UserQuery idEqualTo(Integer id) {
example.createCriteria().andIdEqualTo(id);
return this;
}
// 其他條件方法...
public UserExample build() {
return example;
}
}
// 使用封裝的查詢條件構(gòu)建器
List<User> users = userMapper.selectByExample(new UserQuery().idEqualTo(1).build());六、總結(jié)
通過(guò)以上步驟,我們成功配置了 MyBatis Generator 以生成接口和 XML 映射文件。在實(shí)際開(kāi)發(fā)中,合理使用 MyBatis Generator 可以顯著提高開(kāi)發(fā)效率,減少手動(dòng)編寫重復(fù)代碼的工作量。不同的 targetRuntime 風(fēng)格各有優(yōu)缺點(diǎn),根據(jù)項(xiàng)目的具體需求選擇合適的風(fēng)格可以更好地滿足開(kāi)發(fā)需求。
生成的 Example 類雖然功能強(qiáng)大,但也可能導(dǎo)致代碼冗余和可讀性差。通過(guò)選擇合適的風(fēng)格或自定義生成策略,可以有效解決這些問(wèn)題,使代碼更加簡(jiǎn)潔和易于維護(hù)。
到此這篇關(guān)于MyBatis Generator配置生成接口和XML映射文件的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)MyBatis Generator 生成接口和XML映射文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringCloud Alibaba項(xiàng)目實(shí)戰(zhàn)之nacos-server服務(wù)搭建過(guò)程
Nacos 是阿里巴巴推出來(lái)的一個(gè)新開(kāi)源項(xiàng)目,這是一個(gè)更易于構(gòu)建云原生應(yīng)用的動(dòng)態(tài)服務(wù)發(fā)現(xiàn)、配置管理和服務(wù)管理平臺(tái)。本章節(jié)重點(diǎn)給大家介紹SpringCloud Alibaba項(xiàng)目實(shí)戰(zhàn)之nacos-server服務(wù)搭建過(guò)程,感興趣的朋友一起看看吧2021-06-06
java.lang.OutOfMemoryError: Metaspace異常解決的方法
這篇文章主要介紹了java.lang.OutOfMemoryError: Metaspace異常解決的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
socket編程時(shí)的發(fā)送與接收數(shù)據(jù)時(shí)的問(wèn)題解析
這篇文章主要為大家介紹了socket編程時(shí)的發(fā)送與接收數(shù)據(jù)時(shí)的問(wèn)題解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
SpringBoot統(tǒng)一返回結(jié)果問(wèn)題
這篇文章主要介紹了SpringBoot統(tǒng)一返回結(jié)果問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07
Spring boot 在idea中添加熱部署插件的圖文教程
這篇文章主要介紹了Spring boot 在idea中添加熱部署插件的圖文教程,本文通過(guò)圖文并茂的形式給大家展示具體步驟,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-10-10
@Autowired與@Resource在實(shí)現(xiàn)對(duì)象注入時(shí)的區(qū)別
這篇文章主要介紹了@Autowired與@Resource在實(shí)現(xiàn)對(duì)象注入時(shí)的區(qū)別,有需要的朋友可以借鑒參考下,希望能夠有所幫助2023-04-04

