在使用 mybatis 进行项目开发时,mybatis generator(mbg)是一个非常实用的工具,它能够根据数据库表结构自动生成实体类、mapper 接口以及 xml 映射文件,大大提高了开发效率。本文将详细介绍如何配置 mybatis generator 以生成接口和 xml 映射文件,并对不同的 targetruntime
风格进行介绍和推荐。
一、环境准备
在开始之前,确保你的项目中已经添加了 mybatis generator 的相关依赖。如果你使用的是 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
目录下创建 generatorconfig.xml
配置文件,以下是详细的配置内容及注释:
<?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"> <!-- 自动检查关键字,为关键字增加反引号,如:`type` --> <property name="autodelimitkeywords" value="true"/> <property name="beginningdelimiter" value="`"/> <property name="endingdelimiter" value="`"/> <!-- 指定生成的 java 文件编码 --> <property name="javafileencoding" value="utf-8"/> <!-- 对生成的注释进行控制 --> <commentgenerator> <!-- 由于此插件生成的注释不太美观,这里设置不生成任何注释 --> <property name="suppressallcomments" value="true"/> </commentgenerator> <!-- 数据库链接 --> <jdbcconnection driverclass="com.mysql.cj.jdbc.driver" connectionurl="jdbc:mysql://127.0.0.1:3306/your_database" userid="your_username" password="your_password"> <!-- 解决多个重名的表生成表结构不一致问题 --> <property name="nullcatalogmeanscurrent" value="true"/> </jdbcconnection> <!-- 不强制将所有的数值类型映射为 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 指定数据库中的表名,domainobjectname 指定生成的实体类名 --> <!-- 要生成对应表配置,若想要生成全部表 使用 tablename="%" 即可 --> <!-- 订单详情表 --> <table tablename="order_detail" domainobjectname="orderdetail" <!-- 不生成example --> enablecountbyexample="false" enabledeletebyexample="false" enableselectbyexample="false" enableupdatebyexample="false"> <!-- 自增主键列 --> <generatedkey column="id" sqlstatement="mysql" identity="true"/> <!-- 根据实际需求添加其他列的映射配置 --> </table> </context> </generatorconfiguration>
三、生成代码
在项目根目录下打开终端,运行以下命令生成代码:
mvn mybatis-generator:generate
或者点击 mybatis-generator 组件
运行命令后,mybatis generator 会根据 generatorconfig.xml
配置文件生成 mapper 接口和对应的 xml 映射文件。
四、不同 targetruntime 风格介绍和推荐
1. mybatis3
描述:生成兼容 mybatis 3.x 的代码。这是最常用的目标,支持 mybatis 的基础功能,生成 example 类、sql 语句和常规的 mapper 接口。
使用场景:当使用 mybatis 3.x 时,这是最常见的选择。
推荐:如果你的项目需要使用 mybatis 3.x 的所有功能,包括复杂的查询和条件类,选择
mybatis3
风格是一个不错的选择。
2. mybatis3simple
描述:生成更加简化的代码,省略了 example 类和其他复杂功能。
使用场景:当项目不需要复杂查询或额外的功能时,可以选择该选项,以减少生成的代码量。
推荐:如果你的项目只需要基本的 crud 操作,不需要复杂的查询条件,选择
mybatis3simple
风格可以减少生成的代码量,使项目更加简洁。
3. mybatis3dynamicsql
描述:生成使用 mybatis3 风格的动态 sql 的代码。该选项支持通过 mybatis 提供的动态 sql 功能(如 example 类、criteria 和动态 sql 构建器)生成更加灵活和复杂的 sql 查询。
使用场景:如果你需要动态生成复杂的 sql 语句,并使用 mybatis 3.x 的动态 sql 构建功能,选择该选项。
推荐:官方推荐使用
mybatis3dynamicsql
风格,因为它提供了更高的灵活性和更强大的动态 sql 支持,使用 lambda 表达式可以避免条件对象渗透到上一层,代码更加简洁和易于维护。
4. mybatis3kotlin
描述:生成 kotlin 代码。
使用场景:如果你的项目使用 kotlin 语言,可以选择该选项。
推荐:如果你的项目是基于 kotlin 开发的,选择
mybatis3kotlin
风格可以生成与 kotlin 语言兼容的代码,利用 kotlin 的语言特性,使代码更加简洁和高效。
五、生成的 example 类及解决办法
1. 生成的 example 类
当使用 mybatis3
风格时,mybatis generator 会生成 example 类,这些类用于构建复杂的查询条件。例如,生成的 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 表达式来构建查询条件,使代码更加简洁和易于理解。例如:
list<user> users = usermapper.selectmany(selectstatementprovider.builder() .select(userdynamicsqlsupport.id, userdynamicsqlsupport.name, userdynamicsqlsupport.email) .from(userdynamicsqlsupport.user) .where(userdynamicsqlsupport.name, isequalto("张三")) .build());
封装查询条件:可以封装查询条件的构建逻辑,使代码更加模块化和易于维护。例如,可以创建一个查询条件构建器类,将复杂的查询条件封装起来:
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; } } // 使用封装的查询条件构建器 list<user> users = usermapper.selectbyexample(new userquery().idequalto(1).build());
六、总结
通过以上步骤,我们成功配置了 mybatis generator 以生成接口和 xml 映射文件。在实际开发中,合理使用 mybatis generator 可以显著提高开发效率,减少手动编写重复代码的工作量。不同的 targetruntime
风格各有优缺点,根据项目的具体需求选择合适的风格可以更好地满足开发需求。
生成的 example 类虽然功能强大,但也可能导致代码冗余和可读性差。通过选择合适的风格或自定义生成策略,可以有效解决这些问题,使代码更加简洁和易于维护。
到此这篇关于mybatis generator配置生成接口和xml映射文件的实现的文章就介绍到这了,更多相关mybatis generator 生成接口和xml映射文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论