引言
mybatis作为一款优秀的持久层框架,其最强大的特性之一就是动态sql功能。在实际开发中,我们经常需要根据不同的业务条件构建灵活的sql查询,比如多条件搜索、动态更新字段、批量操作等场景。如果使用传统的jdbc方式手动拼接sql,不仅代码冗余、维护困难,还容易出现sql语法错误和注入风险。
mybatis通过提供一组功能强大的动态标签,让我们能够以声明式的方式动态构建sql语句,极大地提升了开发效率和代码质量。这些标签基于ognl表达式实现,能够根据运行时条件智能生成sql,避免了手动拼接sql的复杂性和风险。
核心标签详解
1. <if> 标签
功能说明:<if>标签是最基础的条件判断标签,根据test属性中的ognl表达式结果决定是否包含对应的sql片段。
完整示例:
<select id="finduserbycondition" resulttype="user">
select * from user
where 1=1
<if test="username != null and username != ''">
and username like concat('%', #{username}, '%')
</if>
<if test="age != null">
and age = #{age}
</if>
<if test="email != null and email != ''">
and email = #{email}
</if>
</select>注意事项:
- 数值类型判断时,只需要判断是否为null,不要判断是否等于空字符串
- 字符串类型需要同时判断null和空字符串
- 多个if标签拼接时要注意and/or的处理,建议配合where标签使用
2. <where> 标签
功能说明:<where>标签智能处理where子句,只有在内部有条件时才插入where关键字,并且自动去除开头多余的and或or,避免了"where 1=1"这种写法。
完整示例:
<select id="findusersmart" resulttype="user">
select * from user
<where>
<if test="username != null and username != ''">
and username like concat('%', #{username}, '%')
</if>
<if test="age != null">
and age = #{age}
</if>
<if test="status != null">
and status = #{status}
</if>
</where>
</select>注意事项:
- 只能去除开头的and/or,无法处理末尾的多余字符
- 当所有条件都为空时,不会生成where子句
- 内部的条件建议都加上and或or前缀
3. <choose>、<when>、<otherwise> 标签
功能说明:
这组标签类似于java中的switch-case语句,实现多条件分支选择。按顺序判断when条件,一旦某个条件满足就执行对应分支,都不满足时执行otherwise。
完整示例:
<select id="finduserbypriority" resulttype="user">
select * from user
<where>
<choose>
<when test="username != null and username != ''">
and username = #{username}
</when>
<when test="email != null and email != ''">
and email = #{email}
</when>
<otherwise>
and status = 'active'
</otherwise>
</choose>
</where>
</select>注意事项:
- when条件是按顺序判断的,只执行第一个满足条件的分支
- otherwise是可选的,类似于default分支
- 适合互斥条件的场景,避免多个if嵌套
4. <set> 标签
功能说明:<set>标签专门用于update语句,智能处理set关键字,自动去除末尾多余的逗号。
完整示例:
<update id="updateuserselective" parametertype="user">
update user
<set>
<if test="username != null and username != ''">
username = #{username},
</if>
<if test="password != null and password != ''">
password = #{password},
</if>
<if test="age != null">
age = #{age},
</if>
<if test="email != null">
email = #{email},
</if>
<if test="status != null">
status = #{status},
</if>
</set>
where id = #{id}
</update>注意事项:
- 每个if条件后都要加逗号
- 至少要有一个字段被更新,否则sql语法错误
- where条件不要放在set标签内部
5. <trim> 标签
功能说明:<trim>标签是最灵活的字符串处理标签,可以自定义添加或删除sql片段的前缀、后缀。
属性说明:
- prefix:添加前缀
- suffix:添加后缀
- prefixoverrides:去除指定的前缀字符
- suffixoverrides:去除指定的后缀字符
完整示例:
<!-- 替代where标签 -->
<select id="finduserbytrim" resulttype="user">
select * from user
<trim prefix="where" prefixoverrides="and |or ">
<if test="username != null">
and username = #{username}
</if>
<if test="age != null">
or age = #{age}
</if>
</trim>
</select>
<!-- 替代set标签 -->
<update id="updateuserbytrim" parametertype="user">
update user
<trim prefix="set" suffixoverrides=",">
<if test="username != null">username = #{username},</if>
<if test="age != null">age = #{age},</if>
<if test="email != null">email = #{email},</if>
</trim>
where id = #{id}
</update>注意事项:
- prefixoverrides中的多个字符之间要用空格分隔(如"and |or ")
- 可以实现where和set标签的所有功能
- 注意空格的处理,避免sql语法错误
6. <foreach> 标签
功能说明:<foreach>标签用于遍历集合,常用于in查询、批量插入、批量删除等场景。
属性说明:
- collection:集合参数名
- item:当前迭代元素的变量名
- index:当前迭代索引(可选)
- open:遍历开始时的字符串
- close:遍历结束时的字符串
- separator:元素之间的分隔符
完整示例:
<!-- in查询 -->
<select id="finduserbyids" resulttype="user">
select * from user
where id in
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</select>
<!-- 批量插入 -->
<insert id="batchinsertusers">
insert into user (username, age, email) values
<foreach collection="users" item="user" separator=",">
(#{user.username}, #{user.age}, #{user.email})
</foreach>
</insert>
<!-- 批量删除 -->
<delete id="batchdeleteusers">
delete from user
where id in
<foreach collection="idlist" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</delete>注意事项:
- list集合默认collection名为"list"或"collection"
- 数组默认collection名为"array"
- 使用@param注解可以自定义collection名称
- 注意批量操作的数据量,避免sql过长
7. <bind> 标签
功能说明:<bind>标签用于创建一个变量并绑定到上下文中,常用于预处理参数,比如模糊查询的通配符拼接。
完整示例:
<select id="finduserbypattern" resulttype="user">
<bind name="pattern" value="'%' + username + '%'" />
select * from user
where username like #{pattern}
</select>
<select id="finduserbydaterange" resulttype="user">
<bind name="startdate" value="startdate + ' 00:00:00'" />
<bind name="enddate" value="enddate + ' 23:59:59'" />
select * from user
where create_time between #{startdate} and #{enddate}
</select>注意事项:
- 可以使用ognl表达式进行复杂的计算
- 创建的变量只在当前sql语句中有效
- 适合复杂的字符串处理和日期处理
8. <sql> 和 <include> 标签
功能说明:
这组标签用于定义可重用的sql片段,提高代码复用性和维护性。
完整示例:
<!-- 定义可复用的sql片段 -->
<sql id="userbasecolumns">
id, username, password, age, email, status, create_time, update_time
</sql>
<sql id="userbasequery">
select <include refid="userbasecolumns" />
from user
</sql>
<!-- 使用sql片段 -->
<select id="findallusers" resulttype="user">
<include refid="userbasequery" />
where status = 'active'
</select>
<select id="finduserbyid" resulttype="user">
<include refid="userbasequery" />
where id = #{id}
</select>
<!-- 带参数的sql片段 -->
<sql id="usercondition">
<if test="username != null and username != ''">
and username like concat('%', #{username}, '%')
</if>
<if test="status != null">
and status = #{status}
</if>
</sql>
<select id="searchusers" resulttype="user">
<include refid="userbasequery" />
<where>
<include refid="usercondition" />
</where>
</select>注意事项:
- sql片段可以包含动态标签
- 可以嵌套使用include标签
- 合理提取公共sql片段,避免过度抽象
综合案例
用户查询综合案例
下面是一个包含多个动态标签组合使用的完整示例,展示了实际开发中的应用场景:
<!-- 用户综合查询接口 -->
<select id="finduserscomprehensive" resulttype="user">
select
u.id, u.username, u.age, u.email, u.status,
u.create_time, u.update_time
from user u
<where>
<!-- 基础条件 -->
<if test="username != null and username != ''">
and u.username like concat('%', #{username}, '%')
</if>
<!-- 状态多选 -->
<if test="statuslist != null and statuslist.size() > 0">
and u.status in
<foreach collection="statuslist" item="status" open="(" separator="," close=")">
#{status}
</foreach>
</if>
<!-- 年龄范围 -->
<if test="minage != null">
and u.age >= #{minage}
</if>
<if test="maxage != null">
and u.age <= #{maxage}
</if>
<!-- 创建时间范围 -->
<if test="starttime != null">
and u.create_time >= #{starttime}
</if>
<if test="endtime != null">
and u.create_time <= #{endtime}
</if>
<!-- 优先级选择 -->
<choose>
<when test="email != null and email != ''">
and u.email = #{email}
</when>
<when test="phone != null and phone != ''">
and u.phone = #{phone}
</when>
</choose>
<!-- id列表 -->
<if test="userids != null and userids.size() > 0">
and u.id in
<foreach collection="userids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</if>
</where>
<!-- 动态排序 -->
<if test="orderby != null and orderby != ''">
order by ${orderby}
<if test="orderdirection != null and orderdirection != ''">
${orderdirection}
</if>
</if>
<!-- 分页 -->
<if test="pagesize != null and pagesize > 0">
limit #{offset}, #{pagesize}
</if>
</select>
<!-- 用户动态更新接口 -->
<update id="updateuserselective" parametertype="user">
update user
<set>
<if test="username != null and username != ''">
username = #{username},
</if>
<if test="password != null and password != ''">
password = #{password},
</if>
<if test="age != null">
age = #{age},
</if>
<if test="email != null and email != ''">
email = #{email},
</if>
<if test="phone != null and phone != ''">
phone = #{phone},
</if>
<if test="status != null">
status = #{status},
</if>
<if test="updatetime != null">
update_time = #{updatetime},
</if>
</set>
where id = #{id}
</update>
<!-- 批量插入用户 -->
<insert id="batchinsertusers" parametertype="java.util.list">
insert into user (username, password, age, email, phone, status, create_time, update_time)
values
<foreach collection="list" item="user" separator=",">
(
#{user.username},
#{user.password},
#{user.age},
#{user.email},
#{user.phone},
#{user.status},
#{user.createtime},
#{user.updatetime}
)
</foreach>
</insert>最佳实践
1. 动态标签选择策略
| 场景 | 推荐标签 | 说明 |
|---|---|---|
| 简单条件判断 | <if> | 最基础的条件判断 |
| 多条件组合查询 | <where> + <if> | 智能处理where和and/or |
| 互斥条件选择 | <choose> + <when> | 避免多个if嵌套 |
| 动态更新字段 | <set> + <if> | 自动处理逗号和set关键字 |
| 自定义字符串处理 | <trim> | 最灵活的字符串处理 |
| 集合遍历操作 | <foreach> | in查询、批量操作 |
| 参数预处理 | <bind> | 模糊查询、日期处理 |
| sql片段复用 | <sql> + <include> | 提取公共sql |
2. 性能优化建议
减少动态判断开销:
<!-- 不推荐:过度动态 -->
<select id="finduser">
select <if test="columns != null">${columns}</if> <if test="columns == null">*</if> from user
</select>
<!-- 推荐:明确字段 -->
<select id="finduser">
select id, username, email from user
<where>
<if test="username != null">
and username = #{username}
</if>
</where>
</select>批量操作优化:
<!-- 推荐:分批次处理,避免sql过长 -->
<insert id="batchinsertusers">
insert into user (username, email) values
<foreach collection="users" item="user" separator=",">
(#{user.username}, #{user.email})
</foreach>
</insert>
<!-- java代码控制批次大小 -->
list<user> users = getuserlist();
int batchsize = 500;
for (int i = 0; i < users.size(); i += batchsize) {
list<user> batch = users.sublist(i, math.min(i + batchsize, users.size()));
usermapper.batchinsertusers(batch);
}3. 安全性注意事项
防止sql注入:
<!-- 危险:直接拼接用户输入 -->
<select id="finduserdangerous">
select * from user order by ${orderby}
</select>
<!-- 安全:白名单校验 -->
<select id="findusersafe">
select * from user
<choose>
<when test="orderby == 'username'">order by username</when>
<when test="orderby == 'create_time'">order by create_time</when>
<otherwise>order by id</otherwise>
</choose>
</select>避免全表操作风险:
<!-- 危险:可能导致全表更新 -->
<update id="updateuserdangerous">
update user
<set>
<if test="status != null">status = #{status}</if>
</set>
<where>
<if test="id != null">id = #{id}</if>
</where>
</update>
<!-- 安全:确保where条件 -->
<update id="updateusersafe">
update user
<set>
status = #{status}
</set>
where id = #{id}
</update>4. 代码可维护性
提取公共sql片段:
<!-- 定义公共字段 -->
<sql id="usercommonfields">
id, username, email, status, create_time
</sql>
<!-- 定义公共条件 -->
<sql id="usercommoncondition">
status = 'active'
and delete_flag = 0
</sql>
<!-- 使用公共片段 -->
<select id="findactiveusers" resulttype="user">
select <include refid="usercommonfields" />
from user
where <include refid="usercommoncondition" />
</select>注释复杂逻辑:
<!-- 用户查询:支持多条件动态组合
1. username:模糊查询
2. statuslist:多状态选择
3. 时间范围:create_time区间
4. 排序:支持动态排序字段
-->
<select id="finduserscomplex" resulttype="user">
select * from user
<where>
<if test="username != null and username != ''">
and username like concat('%', #{username}, '%')
</if>
<if test="statuslist != null and statuslist.size() > 0">
and status in
<foreach collection="statuslist" item="status"
open="(" separator="," close=")">
#{status}
</foreach>
</if>
</where>
</select>5. 参数校验建议
java层校验:
public list<user> findusers(userquery query) {
// 参数校验
if (query == null) {
query = new userquery();
}
// 集合判空
if (collectionutils.isempty(query.getstatuslist())) {
return collections.emptylist();
}
// 分页参数校验
if (query.getpagesize() != null && query.getpagesize() > 100) {
query.setpagesize(100); // 限制最大页数
}
return usermapper.findusers(query);
}xml层安全判断:
<select id="finduserssafe" resulttype="user">
select * from user
<where>
<!-- 双重判空保护 -->
<if test="username != null and username != ''">
and username = #{username}
</if>
<!-- 集合安全判断 -->
<if test="statuslist != null and statuslist.size() > 0">
and status in
<foreach collection="statuslist" item="status"
open="(" separator="," close=")">
#{status}
</foreach>
</if>
</where>
</select>总结
mybatis的动态标签为开发者提供了强大而灵活的sql构建能力,通过合理使用这些标签,我们可以:
- 提升开发效率:避免手动拼接sql的繁琐工作
- 增强代码可读性:声明式的sql构建更直观易懂
- 保证sql安全性:通过预编译防止sql注入
- 提高维护性:sql与业务逻辑分离,便于维护
在实际应用中,需要根据具体场景选择合适的动态标签,并遵循性能优化和安全性的最佳实践,避免过度使用动态标签导致的复杂性问题。
参考资料:
推荐阅读:
- 《mybatis从入门到精通》- 动态sql章节
- 《深入理解mybatis技术原理与实战》- sql映射详解
- mybatis-plus官方文档 - 动态sql增强功能
到此这篇关于mybatis动态标签详解与应用实践的文章就介绍到这了,更多相关mybatis动态标签内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论