告别繁琐的sql拼接,让动态查询像搭积木一样简单
一、为什么需要动态sql?
在实际开发中,我们经常会遇到需要根据不同的条件拼接sql语句的场景。传统的做法是使用java代码进行字符串拼接,但这种方式不仅代码冗余、易出错,还存在sql注入的风险。mybatis提供的动态sql机制,允许我们在xml映射文件中使用标签来构建灵活的sql语句,让代码更清晰、更安全。
核心优势:
- 无需手动处理多余的空格、and/or、逗号分隔符
- 基于ognl表达式,与java对象无缝集成
- 提升可维护性,sql结构一目了然
二、动态sql的执行流程
mybatis在解析动态sql时,会根据传入的参数动态生成最终的sql语句。下图展示了从xml到预编译sql的完整过程:

三、常用动态sql标签详解
1.<if>– 条件判断
最简单的条件标签,当条件满足时拼接sql片段。
语法:
<if test="条件表达式">
sql片段
</if>示例: 根据姓名和年龄动态查询用户
<select id="findusers" resulttype="user">
select * from user where 1=1
<if test="name != null and name != ''">
and name = #{name}
</if>
<if test="age != null and age > 0">
and age = #{age}
</if>
</select>注意: where 1=1 是为了防止所有条件都不满足时出现语法错误。更好的替代方案是使用 <where> 标签。
2.<where>– 智能处理查询条件
自动处理and/or关键字,并去除多余的连接词。
示例: 重构上面的查询
<select id="findusers" resulttype="user">
select * from user
<where>
<if test="name != null and name != ''">
and name = #{name}
</if>
<if test="age != null and age > 0">
and age = #{age}
</if>
</where>
</select>当 name 有值而 age 为 null 时,生成的sql为:
select * from user where name = ?<where>标签会自动去掉开头的and。
3.<set>– 动态更新字段
在 <update> 语句中智能处理逗号分隔符。
示例: 动态更新用户信息
<update id="updateuser">
update user
<set>
<if test="name != null">name = #{name},</if>
<if test="age != null">age = #{age},</if>
<if test="email != null">email = #{email},</if>
</set>
where id = #{id}
</update>
<set> 会自动去掉末尾多余的逗号,并保证至少有一个字段被更新。
4.<foreach>– 遍历集合/数组
常用于 in 查询、批量插入、批量删除。
属性说明:
| 属性 | 作用 |
|---|---|
collection | 要遍历的集合/数组名称 |
item | 每次迭代的当前元素别名 |
index | 当前元素的索引(或map的key) |
open | 遍历开始拼接的字符串 |
close | 遍历结束拼接的字符串 |
separator | 元素之间的分隔符 |
示例1: 批量查询(in条件)
<select id="findbyids" resulttype="user">
select * from user where id in
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</select>
示例2: 批量插入
<insert id="batchinsert">
insert into user (name, age) values
<foreach collection="list" item="user" separator=",">
(#{user.name}, #{user.age})
</foreach>
</insert>
常见坑点: collection 默认支持 list、array、map。如果是自定义参数名,需要使用 @param 注解指定。
5.<trim>– 自定义前缀/后缀处理
<where> 和 <set> 本质上都是 <trim> 的快捷方式,当需要更精细的控制时可直接使用 <trim>。
属性:
prefix– 整体前添加的字符串suffix– 整体后添加的字符串prefixoverrides– 去除前缀中的指定字符串suffixoverrides– 去除后缀中的指定字符串
等价关系:
<!-- <where> 等价于 -->
<trim prefix="where" prefixoverrides="and |or ">
...
</trim>
<!-- <set> 等价于 -->
<trim prefix="set" suffixoverrides=",">
...
</trim>
自定义示例: 动态添加 order by 子句
<select id="selectwithorder" resulttype="user">
select * from user
<trim prefix="order by" suffixoverrides=",">
<if test="orderbyname">name,</if>
<if test="orderbyage">age,</if>
</trim>
</select>
6.<choose> / <when> / <otherwise>– 分支选择
类似java的 switch-case,只执行第一个满足条件的分支。

示例: 按优先级排序查询(姓名优先,否则年龄,否则默认)
<select id="finduserswithpriority" resulttype="user">
select * from user
<where>
<choose>
<when test="name != null">
and name like concat('%', #{name}, '%')
</when>
<when test="age != null">
and age = #{age}
</when>
<otherwise>
and status = 'active'
</otherwise>
</choose>
</where>
</select>
四、综合实战:员工管理系统动态查询
下面是一个结合多个标签的完整示例:
<mapper namespace="com.example.employeemapper">
<!-- 动态查询员工 -->
<select id="searchemployees" resulttype="employee">
select * from employee
<where>
<if test="deptid != null">
and dept_id = #{deptid}
</if>
<if test="minsalary != null">
and salary >= #{minsalary}
</if>
<if test="maxsalary != null">
and salary <= #{maxsalary}
</if>
<if test="keywords != null and keywords != ''">
and (name like concat('%', #mybatis动态sql封装,mybatis动态sql使用,mybatis动态sql,mybatis sql, '%')
or position like concat('%', #mybatis动态sql封装,mybatis动态sql使用,mybatis动态sql,mybatis sql, '%'))
</if>
<choose>
<when test="hiredatestart != null and hiredateend != null">
and hire_date between #{hiredatestart} and #{hiredateend}
</when>
<when test="hiredatestart != null">
and hire_date >= #{hiredatestart}
</when>
<when test="hiredateend != null">
and hire_date <= #{hiredateend}
</when>
</choose>
</where>
<if test="orderby != null">
<trim prefix="order by" suffixoverrides=",">
<if test="orderby.name">name,</if>
<if test="orderby.salary">salary,</if>
<if test="orderby.hiredate">hire_date,</if>
</trim>
</if>
</select>
</mapper>
五、最佳实践与常见问题
推荐做法
- 优先使用
<where>/<set>而非手写1=1或set后跟逗号。 - 结合
<trim>处理复杂的动态前缀/后缀逻辑。 - 使用
@param为集合参数命名,避免依赖默认的list/array。 - 对字符串判空:
test="name != null and name != ''"。
常见错误
| 错误现象 | 原因 | 解决方案 |
|---|---|---|
| 动态sql不生效 | 忘记在<select>中嵌入动态标签 | 检查标签是否正确嵌套 |
| 多余的and/or | 条件未全部满足时前缀残留 | 使用<where>或<trim prefixoverrides> |
| 批量插入性能差 | foreach生成超大sql | 改用分批处理或jdbc batch |
| ognl表达式异常 | 使用了java的&&/` |
六、总结
mybatis的动态sql通过一套简洁的xml标签,完美解决了传统jdbc拼接sql的痛点。掌握以下核心标签即可应对90%的动态场景:
| 标签 | 核心用途 |
|---|---|
<if> | 简单条件判断 |
<where> | 智能查询条件组装 |
<set> | 智能更新字段组装 |
<foreach> | 遍历集合(in、批量操作) |
<trim> | 自定义前缀/后缀处理 |
<choose> | 多分支互斥选择 |
动态sql的本质是在xml层面基于ognl表达式进行零逻辑的sql片段组合。理解这一思想后,你可以灵活组合这些标签,写出既优雅又安全的动态sql。
延伸思考: 如果动态条件非常复杂(超过5个分支),建议考虑将部分逻辑迁移到java层,使用@selectprovider注解或构建查询对象模式,以保持xml的可读性。
到此这篇关于一文详解mybatis中动态sql的封装原理与常用标签实战应用的文章就介绍到这了,更多相关mybatis动态sql应用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论