深入理解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语句的清晰和可维护性。
登录后查看全文
热门项目推荐
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust0151- DDeepSeek-V4-ProDeepSeek-V4-Pro(总参数 1.6 万亿,激活 49B)面向复杂推理和高级编程任务,在代码竞赛、数学推理、Agent 工作流等场景表现优异,性能接近国际前沿闭源模型。Python00
LongCat-Video-Avatar-1.5最新开源LongCat-Video-Avatar 1.5 版本,这是一款经过升级的开源框架,专注于音频驱动人物视频生成的极致实证优化与生产级就绪能力。该版本在 LongCat-Video 基础模型之上构建,可生成高度稳定的商用级虚拟人视频,支持音频-文本转视频(AT2V)、音频-文本-图像转视频(ATI2V)以及视频续播等原生任务,并能无缝兼容单流与多流音频输入。00
auto-devAutoDev 是一个 AI 驱动的辅助编程插件。AutoDev 支持一键生成测试、代码、提交信息等,还能够与您的需求管理系统(例如Jira、Trello、Github Issue 等)直接对接。 在IDE 中,您只需简单点击,AutoDev 会根据您的需求自动为您生成代码。Kotlin03
Intern-S2-PreviewIntern-S2-Preview,这是一款高效的350亿参数科学多模态基础模型。除了常规的参数与数据规模扩展外,Intern-S2-Preview探索了任务扩展:通过提升科学任务的难度、多样性与覆盖范围,进一步释放模型能力。Python00
skillhubopenJiuwen 生态的 Skill 托管与分发开源方案,支持自建与可选 ClawHub 兼容。Python0111
项目优选
收起
暂无描述
Dockerfile
731
4.74 K
Ascend Extension for PyTorch
Python
610
794
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
1 K
1.01 K
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
433
392
华为昇腾面向大规模分布式训练的多模态大模型套件,支撑多模态生成、多模态理解。
Python
145
237
Claude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed.
Get Started
Rust
1.16 K
150
暂无简介
Dart
983
252
Oohos_react_native
React Native鸿蒙化仓库
C++
348
401
昇腾LLM分布式训练框架
Python
166
198
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
1.67 K
987