MyBatis Generator配置生成接口和XML映射文件的實現(xiàn)
在使用 MyBatis 進行項目開發(fā)時,MyBatis Generator(MBG)是一個非常實用的工具,它能夠根據(jù)數(shù)據(jù)庫表結(jié)構(gòu)自動生成實體類、Mapper 接口以及 XML 映射文件,大大提高了開發(fā)效率。本文將詳細介紹如何配置 MyBatis Generator 以生成接口和 XML 映射文件,并對不同的 targetRuntime 風格進行介紹和推薦。
一、環(huán)境準備
在開始之前,確保你的項目中已經(jīng)添加了 MyBatis Generator 的相關(guān)依賴。如果你使用的是 Maven 項目,可以在 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 配置文件,以下是詳細的配置內(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 唯一標識,targetRuntime 指定生成代碼的方式,風格 MyBatis3DynamicSql,MyBatis3,MyBatis3Simple,MyBatis3Kotlin -->
<context id="mysqlTables" targetRuntime="MyBatis3" defaultModelType="flat">
<!-- 自動檢查關(guān)鍵字,為關(guān)鍵字增加反引號,如:`type` -->
<property name="autoDelimitKeywords" value="true"/>
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<!-- 指定生成的 Java 文件編碼 -->
<property name="javaFileEncoding" value="UTF-8"/>
<!-- 對生成的注釋進行控制 -->
<commentGenerator>
<!-- 由于此插件生成的注釋不太美觀,這里設(shè)置不生成任何注釋 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!-- 數(shù)據(jù)庫鏈接 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://127.0.0.1:3306/your_database"
userId="your_username"
password="your_password">
<!-- 解決多個重名的表生成表結(jié)構(gòu)不一致問題 -->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<!-- 不強制將所有的數(shù)值類型映射為 Java 的 BigDecimal 類型 -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 配置生成實體類的位置和包名 -->
<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ù)庫中的表名,domainObjectName 指定生成的實體類名 -->
<!-- 要生成對應(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ù)實際需求添加其他列的映射配置 -->
</table>
</context>
</generatorConfiguration>三、生成代碼
在項目根目錄下打開終端,運行以下命令生成代碼:
mvn mybatis-generator:generate
或者點擊 mybatis-generator 組件

運行命令后,MyBatis Generator 會根據(jù) generatorConfig.xml 配置文件生成 Mapper 接口和對應(yīng)的 XML 映射文件。
四、不同 targetRuntime 風格介紹和推薦
1. MyBatis3
描述:生成兼容 MyBatis 3.x 的代碼。這是最常用的目標,支持 MyBatis 的基礎(chǔ)功能,生成 Example 類、SQL 語句和常規(guī)的 Mapper 接口。
使用場景:當使用 MyBatis 3.x 時,這是最常見的選擇。
推薦:如果你的項目需要使用 MyBatis 3.x 的所有功能,包括復雜的查詢和條件類,選擇
MyBatis3風格是一個不錯的選擇。
2. MyBatis3Simple
描述:生成更加簡化的代碼,省略了 Example 類和其他復雜功能。
使用場景:當項目不需要復雜查詢或額外的功能時,可以選擇該選項,以減少生成的代碼量。
推薦:如果你的項目只需要基本的 CRUD 操作,不需要復雜的查詢條件,選擇
MyBatis3Simple風格可以減少生成的代碼量,使項目更加簡潔。
3. MyBatis3DynamicSql
描述:生成使用 MyBatis3 風格的動態(tài) SQL 的代碼。該選項支持通過 MyBatis 提供的動態(tài) SQL 功能(如 Example 類、Criteria 和動態(tài) SQL 構(gòu)建器)生成更加靈活和復雜的 SQL 查詢。
使用場景:如果你需要動態(tài)生成復雜的 SQL 語句,并使用 MyBatis 3.x 的動態(tài) SQL 構(gòu)建功能,選擇該選項。
推薦:官方推薦使用
MyBatis3DynamicSql風格,因為它提供了更高的靈活性和更強大的動態(tài) SQL 支持,使用 Lambda 表達式可以避免條件對象滲透到上一層,代碼更加簡潔和易于維護。
4. MyBatis3Kotlin
描述:生成 Kotlin 代碼。
使用場景:如果你的項目使用 Kotlin 語言,可以選擇該選項。
推薦:如果你的項目是基于 Kotlin 開發(fā)的,選擇
MyBatis3Kotlin風格可以生成與 Kotlin 語言兼容的代碼,利用 Kotlin 的語言特性,使代碼更加簡潔和高效。
五、生成的 Example 類及解決辦法
1. 生成的 Example 類
當使用 MyBatis3 風格時,MyBatis Generator 會生成 Example 類,這些類用于構(gòu)建復雜的查詢條件。例如,生成的 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. 問題及解決辦法
問題 1:Example 類過于復雜,導致代碼冗余
解決辦法:
使用
MyBatis3Simple風格:如果你的項目不需要復雜的查詢條件,可以選擇MyBatis3Simple風格,這樣可以避免生成 Example 類,減少代碼冗余。自定義生成策略:如果你仍然需要使用
MyBatis3風格,但希望減少 Example 類的復雜性,可以通過自定義生成策略來簡化 Example 類。例如,可以修改generatorConfig.xml文件中的<commentGenerator>配置,減少生成的注釋和不必要的代碼。
問題 2:Example 類的使用導致代碼可讀性差
解決辦法:
使用 Lambda 表達式:在
MyBatis3DynamicSql風格中,可以使用 Lambda 表達式來構(gòu)建查詢條件,使代碼更加簡潔和易于理解。例如:
List<User> users = userMapper.selectMany(SelectStatementProvider.builder()
.select(UserDynamicSqlSupport.id, UserDynamicSqlSupport.name, UserDynamicSqlSupport.email)
.from(UserDynamicSqlSupport.user)
.where(UserDynamicSqlSupport.name, isEqualTo("張三"))
.build());封裝查詢條件:可以封裝查詢條件的構(gòu)建邏輯,使代碼更加模塊化和易于維護。例如,可以創(chuàng)建一個查詢條件構(gòu)建器類,將復雜的查詢條件封裝起來:
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é)
通過以上步驟,我們成功配置了 MyBatis Generator 以生成接口和 XML 映射文件。在實際開發(fā)中,合理使用 MyBatis Generator 可以顯著提高開發(fā)效率,減少手動編寫重復代碼的工作量。不同的 targetRuntime 風格各有優(yōu)缺點,根據(jù)項目的具體需求選擇合適的風格可以更好地滿足開發(fā)需求。
生成的 Example 類雖然功能強大,但也可能導致代碼冗余和可讀性差。通過選擇合適的風格或自定義生成策略,可以有效解決這些問題,使代碼更加簡潔和易于維護。
到此這篇關(guān)于MyBatis Generator配置生成接口和XML映射文件的實現(xiàn)的文章就介紹到這了,更多相關(guān)MyBatis Generator 生成接口和XML映射文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringCloud Alibaba項目實戰(zhàn)之nacos-server服務(wù)搭建過程
Nacos 是阿里巴巴推出來的一個新開源項目,這是一個更易于構(gòu)建云原生應(yīng)用的動態(tài)服務(wù)發(fā)現(xiàn)、配置管理和服務(wù)管理平臺。本章節(jié)重點給大家介紹SpringCloud Alibaba項目實戰(zhàn)之nacos-server服務(wù)搭建過程,感興趣的朋友一起看看吧2021-06-06
java.lang.OutOfMemoryError: Metaspace異常解決的方法
這篇文章主要介紹了java.lang.OutOfMemoryError: Metaspace異常解決的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-03-03
socket編程時的發(fā)送與接收數(shù)據(jù)時的問題解析
這篇文章主要為大家介紹了socket編程時的發(fā)送與接收數(shù)據(jù)時的問題解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-06-06
Spring boot 在idea中添加熱部署插件的圖文教程
這篇文章主要介紹了Spring boot 在idea中添加熱部署插件的圖文教程,本文通過圖文并茂的形式給大家展示具體步驟,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-10-10
@Autowired與@Resource在實現(xiàn)對象注入時的區(qū)別
這篇文章主要介紹了@Autowired與@Resource在實現(xiàn)對象注入時的區(qū)別,有需要的朋友可以借鑒參考下,希望能夠有所幫助2023-04-04

