深入理解MyBatis动态SQL:lcomment/development-recipes项目实践指南
2025-06-25 01:04:04作者:秋泉律Samson
什么是动态SQL
动态SQL是MyBatis框架最强大的特性之一。如果你曾经使用过JDBC或其他类似框架,就会明白根据条件拼接SQL语句是多么痛苦的事情。MyBatis提供了一套强大的动态SQL语言,可以在映射的SQL语句中使用。
MyBatis 3对动态SQL进行了重大改进,采用OGNL(Object-Graph Navigation Language)作为基础表达式语言,使得SQL语句的构建更加灵活和强大。
核心动态SQL元素
1. if条件判断
if元素是最基本的条件判断,允许你在SQL中包含条件性的where子句部分。
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM BLOG
WHERE state = 'ACTIVE'
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</select>
使用技巧:
- 字符串比较:可以使用
==、!=、eq或.equals()方法 - 忽略大小写比较:使用
.equalsIgnoreCase()方法 - 数字比较:支持
>、>=、<、<=等运算符 - 逻辑运算:使用
and代替&&,or代替||
2. choose-when-otherwise多重选择
类似于Java中的switch-case结构,提供多重条件选择:
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM BLOG
WHERE state = 'ACTIVE'
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
3. trim-where-set智能处理
where元素
解决SQL拼接中AND/OR位置问题:
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
</where>
</select>
set元素
动态更新语句解决方案:
<update id="updateAuthorIfNecessary">
update Author
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
</set>
where id=#{id}
</update>
trim元素
更灵活地处理SQL片段:
<!-- 替代where -->
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
<!-- 替代set -->
<trim prefix="SET" suffixOverrides=",">
...
</trim>
4. foreach循环遍历
特别适合构建IN条件:
<select id="selectPostIn" resultType="Post">
SELECT * FROM POST P
<where>
<foreach item="item" index="index" collection="list"
open="ID in (" separator="," close=")" nullable="true">
#{item}
</foreach>
</where>
</select>
支持的数据类型:
- 数组
- 实现了Iterable接口的集合
- Map对象(index为key,item为value)
5. script脚本支持
在注解方式的Mapper接口中使用动态SQL:
@Update({"<script>",
"update Author",
" <set>",
" <if test='username != null'>username=#{username},</if>",
" </set>",
"where id=#{id}",
"</script>"})
void updateAuthorValues(Author author);
6. bind变量绑定
使用OGNL表达式创建变量并绑定到上下文:
<select id="selectBlogsLike" resultType="Blog">
<bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
SELECT * FROM BLOG
WHERE title LIKE #{pattern}
</select>
高级特性
多数据库厂商支持
通过_databaseId变量实现不同数据库的SQL适配:
<insert id="insert">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
<if test="_databaseId == 'oracle'">
select seq_users.nextval from dual
</if>
<if test="_databaseId == 'db2'">
select nextval for seq_users from sysibm.sysdummy1"
</if>
</selectKey>
insert into users values (#{id}, #{name})
</insert>
可插拔脚本语言支持
MyBatis 3.2+支持自定义脚本语言驱动:
public interface LanguageDriver {
ParameterHandler createParameterHandler(...);
SqlSource createSqlSource(...);
}
配置方式:
- 全局默认语言驱动:
<settings>
<setting name="defaultScriptingLanguage" value="myLanguage"/>
</settings>
- 语句级别指定:
<select id="selectBlog" lang="myLanguage">...</select>
- 注解方式指定:
@Lang(MyLanguageDriver.class)
@Select("SELECT * FROM BLOG")
List<Blog> selectBlog();
最佳实践建议
- 复杂条件处理:对于复杂的条件查询,优先使用
where+if组合,避免SQL语法错误 - 批量操作:使用
foreach处理批量插入/更新时,注意数据库对批量语句长度的限制 - 性能考虑:动态SQL虽然灵活,但过度使用可能导致SQL难以维护和优化
- 可读性:对于特别复杂的动态SQL,考虑拆分为多个SQL语句或在业务层处理部分逻辑
- 测试覆盖:动态SQL的各个分支路径都应该有对应的测试用例覆盖
通过合理运用MyBatis的动态SQL特性,可以大大减少重复SQL代码,提高开发效率,同时保持SQL语句的清晰和可维护性。
登录后查看全文
热门项目推荐
GLM-5智谱 AI 正式发布 GLM-5,旨在应对复杂系统工程和长时域智能体任务。Jinja00
LongCat-AudioDiT-1BLongCat-AudioDiT 是一款基于扩散模型的文本转语音(TTS)模型,代表了当前该领域的最高水平(SOTA),它直接在波形潜空间中进行操作。00
jiuwenclawJiuwenClaw 是一款基于openJiuwen开发的智能AI Agent,它能够将大语言模型的强大能力,通过你日常使用的各类通讯应用,直接延伸至你的指尖。Python0245- QQwen3.5-397B-A17BQwen3.5 实现了重大飞跃,整合了多模态学习、架构效率、强化学习规模以及全球可访问性等方面的突破性进展,旨在为开发者和企业赋予前所未有的能力与效率。Jinja00
AtomGit城市坐标计划AtomGit 城市坐标计划开启!让开源有坐标,让城市有星火。致力于与城市合伙人共同构建并长期运营一个健康、活跃的本地开发者生态。01
HivisionIDPhotos⚡️HivisionIDPhotos: a lightweight and efficient AI ID photos tools. 一个轻量级的AI证件照制作算法。Python05
项目优选
收起
deepin linux kernel
C
27
13
OpenHarmony documentation | OpenHarmony开发者文档
Dockerfile
641
4.19 K
Ascend Extension for PyTorch
Python
478
579
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
934
841
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
386
272
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
1.51 K
866
暂无简介
Dart
884
211
仓颉编程语言运行时与标准库。
Cangjie
161
922
昇腾LLM分布式训练框架
Python
139
162
🔥LeetCode solutions in any programming language | 多种编程语言实现 LeetCode、《剑指 Offer(第 2 版)》、《程序员面试金典(第 6 版)》题解
Java
69
21