MyBatis動態(tài)SQL與MyBatis Generator插件使用教程
一.動態(tài)SQL
動態(tài) SQL 是Mybatis的強大特性之?,能夠完成不同條件下不同的 sql 拼接
下面我只介紹比較常用的動態(tài)SQL標簽 ,想要了解更多標簽可以參考官方文檔:https://mybatis.net.cn/dynamic-sql.html
1.1 <if> 標簽
if 標簽 是 MyBatis 動態(tài) SQL 最常用的標簽,作用是根據(jù)條件動態(tài)拼接 SQL 片段,解決「不同條件下執(zhí)行不同 SQL」的問題,比如多條件查詢、非空字段更新 / 插入等場景。
語法:
<if test="條件表達式">
需要拼接的 SQL 片段
</if>接口定義:
Integer insertUserByCondition(UserInfo userInfo);
Mapper.xml 實現(xiàn):
<insert id="insertUserByCondition">
INSERT INTO userinfo (
username,
`password`,
age,
<if test="gender != null">
gender,
</if>
phone)
VALUES (
#{username},
#{age},
<if test="gender != null">
#{gender},
</if>
#{phone})
</insert>使用注解實現(xiàn)(不推薦):
把上面SQL(包括標簽),使用<script></script>標簽括起來就可以
@Insert("<script>" +
"INSERT INTO userinfo (username,`password`,age," +
"<if test='gender!=null'>gender,</if>" +
"phone)" +
"VALUES(#{username},#{age}," +
"<if test='gender!=null'>#{gender},</if>" +
"#{phone})"+
"</script>")
Integer insertUserByCondition(UserInfo userInfo);1.2 <trim>標簽
<trim> 是 MyBatis 中用于修剪 SQL 片段首尾多余字符的標簽,常配合<if> 使用,解決「動態(tài)拼接 SQL 時首尾多出 AND/OR/ 逗號」的問題
語法:
<trim prefix="前綴" suffix="后綴" prefixOverrides="要移除的前綴字符" suffixOverrides="要移除的后綴字符">
動態(tài)拼接的 SQL 片段
</trim>| 屬性 | 作用 | 示例值 |
|---|---|---|
prefix | 給拼接后的 SQL 片段添加前綴(比如 ( 或 WHERE) | prefix="WHERE" |
suffix | 給拼接后的 SQL 片段添加后綴(比如 ) 或 VALUES) | suffix=")" |
prefixOverrides | 移除拼接后 SQL 片段開頭的指定字符(比如 AND/OR) | prefixOverrides="AND" |
suffixOverrides | 移除拼接后 SQL 片段結(jié)尾的指定字符(比如 ,) | suffixOverrides="," |
注意:它會根據(jù)內(nèi)部動態(tài)拼接的 SQL 片段,自動決定是否添加前綴 / 后綴,以及是否移除首尾多余的字符,完全不需要我們手動判斷
調(diào)整 Mapper.xml 的插入語句為:
<insert id="insertUserByCondition">
INSERT INTO userinfo
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="username !=null">
username,
</if>
<if test="password !=null">
`password`,
</if>
<if test="age != null">
age,
</if>
<if test="gender != null">
gender,
</if>
<if test="phone != null">
phone,
</if>
</trim>
VALUES
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="username !=null">
#{username},
</if>
<if test="password !=null">
#{password},
</if>
<if test="age != null">
#{age},
</if>
<if test="gender != null">
#{gender},
</if>
<if test="phone != null">
#{phone}
</if>
</trim>
</insert>1.3 <where>標簽
<where> 是 MyBatis 為 WHERE 子句量身定制 的標簽,本質(zhì)是 <trim> 的「簡化版」,專門解決「動態(tài)查詢時 WHERE 子句的拼接問題」,比手動寫<trim> 更簡潔、語義更清晰。
核心語法:
<where>
<if test="條件1">AND/OR 條件1的SQL片段</if>
<if test="條件2">AND/OR 條件2的SQL片段</if>
<!-- 更多if條件 -->
</where>核心作用:
- 自動為條件塊添加
WHERE關(guān)鍵字(僅當內(nèi)部有有效條件時); - 自動剔除條件塊開頭多余的
AND或OR關(guān)鍵字。
注意:<where> 標簽是 <trim perfix="where perfixOverrides = "AND" | "OR" > 的簡化寫法,規(guī)則完全一致。
接口定義:
List<UserInfo> queryByCondition();
Mapper.xml 實現(xiàn):
<select id="queryByCondition" resultType="com.example.demo.model.UserInfo">
select id, username, age, gender, phone, delete_flag, create_time,
update_time
from userinfo
<where>
<if test="age != null">
and age = #{age}
</if>
<if test="gender != null">
and gender = #{gender}
</if>
<if test="deleteFlag != null">
and delete_flag = #{deleteFlag}
</if>
</where>
</select>1.4 <set> 標簽
<set>是 MyBatis 提供的動態(tài) SQL 核心標簽,專用于 UPDATE 語句的 SET子句動態(tài)拼接,是<trim>標簽針對更新場景的語法糖(簡化封裝),其核心定義可拆解為:
核心語法:
<update id="方法名" parameterType="參數(shù)類型(如實體類全限定名)">
UPDATE 表名
<set>
<!-- 動態(tài)更新字段:每個字段后可加逗號,<set> 自動處理 -->
<if test="字段名 != null [and 字段名 != '']">
數(shù)據(jù)庫字段名 = #{參數(shù)名},
</if>
<!-- 可添加多個 <if> 標簽,對應多個更新字段 -->
</set>
WHERE 主鍵字段 = #{主鍵參數(shù)} <!-- 必須加,防止全表更新 -->
</update>功能定位:解決手動拼接 UPDATE 語句的 SET 子句時,因字段條件動態(tài)變化導致的「末尾多余逗號」「無有效字段時生成空 SET 子句」等 SQL 語法錯誤問題;
核心規(guī)則:
- 僅當內(nèi)部包含有效更新字段(非空的
<if>條件塊)時,才會在拼接結(jié)果前添加SET關(guān)鍵字; - 自動剔除拼接結(jié)果末尾多余的英文逗號(
,); - 無有效更新字段時,不生成任何
SET相關(guān)內(nèi)容(避免UPDATE table WHERE ...這類語法錯誤)。
注意:<set> 標簽也可以使用 <trim prefix="set" suffixOverrides=","> 代替,這兩個的功能完全一致
接口定義:
Integer updateUserByCondition(UserInfo userInfo);
Mapper.xml 實現(xiàn):
<update id="updateUserByCondition">
update userinfo
<set>
<if test="username != null">
username = #{username},
</if>
<if test="age != null">
age = #{age},
</if>
<if test="deleteFlag != null">
delete_flag = #{deleteFlag},
</if>
</set>
where id = #{id}
</update>1.5 <foreach>標簽
<foreach>標簽是 MyBatis 框架中最常用的動態(tài) SQL 標簽之一,核心作用是遍歷集合(List/Set/ 數(shù)組 / Map),并根據(jù)集合元素動態(tài)拼接 SQL 語句(比如批量插入、IN 條件查詢等)。
<foreach>標簽的核心屬性如下(前 4 個是最常用的):
| 屬性名 | 作用 |
|---|---|
collection | 綁定方法參數(shù)中的集合,如List,Set,Map或數(shù)組對象 |
item | 遍歷時的每一個對象,給每一個對象取的別名 |
separator | 元素之間的分隔符 |
open | 語句塊開頭的字符串 |
close | 語句塊結(jié)尾得字符串 |
接口定義:
void deleteByIds(List<Integer> ids);
Mapper.xml 實現(xiàn):
<delete id="deleteByIds">
delete from userinfo
where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>1.6 <include> 標簽
<include> 標簽是 MyBatis 中用于復用 SQL 片段的核心標簽,能有效解決 SQL 代碼冗余問題(比如多個 SQL 語句共用相同的字段列表、WHERE 條件等),提升代碼的可維護性。
簡單來說,<include>就像編程里的 “復制粘貼”,但更優(yōu)雅 —— 你可以把重復的 SQL 片段定義在<sql> 標簽里,然后在需要的地方用<include>引用它。
核心語法:
1. 定義可復用的sql片段(使用 <sql> 標簽)
<sql id="allColumn"> id, username, age, gender, phone, delete_flag, create_time, update_time </sql>
2. 引用sql片段 (使用<include> 標簽)
<select id="queryAllUser" resultMap="BaseMap">
select
<include refid="allColumn"></include>
from userinfo
</select>
<select id="queryById" resultType="com.example.demo.model.UserInfo">
select
<include refid="allColumn"></include>
from userinfo where id= #{id}
</select>總結(jié)使用流程:先通過<sql id="xxx">定義片段,再通過<include refid ="xxx">引用;
二. MyBatis Generator
MyBatis Generator是?個為MyBatis框架設(shè)計的代碼成成?具, 它可以根據(jù)數(shù)據(jù)庫表結(jié)構(gòu)自動生成相應 的Java 實體類 , Mapper接口 以及SQL映射文件,簡化數(shù)據(jù)訪問層的編碼工作,使得開發(fā)者可以更專注于 業(yè)務邏輯的實現(xiàn). 接下來我們看下,如何使用 MyBatisGenerator來生成代碼.
2.1 引入插件
<plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.6</version> <executions> <execution> <id>Generate MyBatis Artifacts</id> <phase>deploy</phase> <goals> <goal>generate</goal> </goals> </execution> </executions> <configuration> <!--generator配置?件所在位置 --> <configurationFile>src/main/resources/mybatisGenerator/generatorConfig.xml</con figurationFile> <!-- 允許覆蓋?成的?件, mapxml不會覆蓋, 采?追加的?式--> <overwrite>true</overwrite> <verbose>true</verbose> <!--將當前pom的依賴項添加到?成器的類路徑中--> <includeCompileDependencies>true</includeCompileDependencies> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> </dependency> </dependencies> </plugin>
上面的有些內(nèi)容屬于模板,實際需要按情況進行修改,比如<configurationFile>中的路徑要和你創(chuàng)建的文件的路徑保持一致
2.2 添加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> <!-- ?個數(shù)據(jù)庫?個context --> <context id="MysqlTables" targetRuntime="MyBatis3Simple"> <!--禁??動?成的注釋--> <commentGenerator> <property name="suppressDate" value="true"/> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--數(shù)據(jù)庫連接信息--> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/java_blog_spring? serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true" userId="root" password="root"> </jdbcConnection> <!-- ?成實體類, 配置路徑 --> <javaModelGenerator targetPackage="com.example.demo.model" targetProject="src/main/java" > <property name="enableSubPackages" value="false"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- ?成mapxml?件 --> <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources" > <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <!-- ?成mapxml對應client,也就是接?mapper --> <javaClientGenerator targetPackage="com.example.demo.mapper" targetProject="src/main/java" type="XMLMAPPER" > <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!-- table可以有多個,tableName表?要匹配的數(shù)據(jù)庫表 --> <table tableName="user" domainObjectName="UserInfo" enableSelectByExample="true" enableDeleteByExample="true" enableDeleteByPrimaryKey="true" enableCountByExample="true" enableUpdateByExample="true">
2.3 生成文件

雙擊運行即可根據(jù) generatorConfig.xml 中的具體配置 生成一個表 的Java實體類,mapper接口,mapper接口對應的XML文件
到此這篇關(guān)于MyBatis動態(tài)SQL與MyBatis Generator插件使用教程的文章就介紹到這了,更多相關(guān)MyBatis Generator插件使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot中快速實現(xiàn)郵箱發(fā)送代碼解析
這篇文章主要介紹了SpringBoot中快速實現(xiàn)郵箱發(fā)送代碼解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-08-08
springboot 如何使用jedis連接Redis數(shù)據(jù)庫
這篇文章主要介紹了springboot 使用jedis連接Redis數(shù)據(jù)庫的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
Java的MyBatis框架中實現(xiàn)多表連接查詢和查詢結(jié)果分頁
這篇文章主要介紹了Java的MyBatis框架中實現(xiàn)多表連接查詢和查詢結(jié)果分頁,借助MyBatis框架中帶有的動態(tài)SQL查詢功能可以比普通SQL查詢做到更多,需要的朋友可以參考下2016-04-04
SpringBoot集成內(nèi)存數(shù)據(jù)庫Sqlite的實踐
sqlite這樣的內(nèi)存數(shù)據(jù)庫,小巧可愛,做小型服務端演示程序,非常好用,本文主要介紹了SpringBoot集成Sqlite,具有一定的參考價值,感興趣的可以了解一下2021-09-09
關(guān)于@DS注解切換數(shù)據(jù)源失敗的原因?qū)崙?zhàn)記錄
項目配置了多個數(shù)據(jù)源,需要使用@DS注解來切換數(shù)據(jù)源,但是卻遇到了問題,下面這篇文章主要給大家介紹了關(guān)于@DS注解切換數(shù)據(jù)源失敗原因的相關(guān)資料,需要的朋友可以參考下2023-05-05

