if 条件判断
<if> 是 MyBatis 动态 SQL 中最基础的条件判断标签,通过 test 属性中的 OGNL 表达式决定是否包含内部 SQL 片段。
基本语法
XML
<if test="条件表达式">
SQL 片段
</if>
条件为 true 时,内部 SQL 片段被拼入最终 SQL。
非空判断
最常见场景是可选查询条件:
XML
<select id="findUser" resultType="User">
SELECT * FROM user
<where>
<if test="name != null">
name LIKE CONCAT('%', #{name}, '%')
</if>
<if test="age != null">
AND age = #{age}
</if>
<if test="email != null and email != ''">
AND email = #{email}
</if>
</where>
</select>
传入 name="张", age=25, email=null 时:
SQL
SELECT * FROM user WHERE name LIKE ? AND age = ?
空字符串判断
区分 null 和空字符串:
XML
<if test="status != null">
AND status = #{status}
</if>
<if test="status != null and status != ''">
AND status = #{status}
</if>
status != null:传入非 null 值(包括空字符串)时执行status != null and status != '':仅传入非空字符串时执行
集合判断
判断 List/Set 是否为空:
XML
<select id="findByIds" resultType="User">
SELECT * FROM user
<where>
<if test="ids != null and ids.size() > 0">
id IN
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</if>
</where>
</select>
布尔值判断
XML
<select id="findByStatus" resultType="User">
SELECT * FROM user
<where>
<if test="onlyActive">
AND status = 'ACTIVE'
</if>
</where>
</select>
复杂表达式
OGNL 支持方法调用和逻辑运算:
XML
<select id="searchUser" resultType="User">
<bind name="keyword" value="keyword.trim()"/>
<where>
<if test="keyword != null and keyword.length() > 0">
name LIKE #{keywordPattern} OR email LIKE #{keywordPattern}
</if>
<if test="minAge != null and maxAge != null and minAge < maxAge">
AND age BETWEEN #{minAge} AND #{maxAge}
</if>
</where>
</select>
字符串等值判断
XML
<select id="findByType" resultType="User">
<where>
<if test='type == "admin"'>
AND role = 'ADMIN'
</if>
<if test='type == "user"'>
AND role = 'USER'
</if>
</where>
</select>
test 属性外层用单引号,内层字符串用双引号,或反过来,避免引号冲突。
OGNL 常用操作
| 操作 | 示例 |
|---|---|
| 非空判断 | test="name != null" |
| 空字符串 | test="name != null and name != ''" |
| 集合长度 | test="list != null and list.size() > 0" |
| 字符串方法 | test="name.trim().length() > 0" |
| 数值比较 | test="age > 18" |
| 逻辑与 | test="a != null and b != null" |
| 逻辑或 | test="a != null or b != null" |
注意事项
- test 属性使用 OGNL 表达式,不是 SQL 表达式
>和<在 XML 中需转义为>和<,或使用<![CDATA[]]>- 字符串比较区分大小写:
test='type == "Admin"' - 空集合
list.isEmpty()返回 true,需结合list != null判断
要点总结
- if 通过 test 属性中的 OGNL 表达式决定是否包含 SQL 片段
- 常用于非空判断、集合判断、字符串比较等场景
!= null判断非空,!= null and != ''判断非空字符串- OGNL 支持方法调用、逻辑运算、集合操作
- 多个 if 并列使用时需注意 AND/OR 的拼接位置,配合 where 标签使用更佳
📝 发现内容有误?点击此处直接编辑