mybatis ifelse
时间: 2025-01-11 18:44:16 浏览: 72
### MyBatis 中 `if` 和 `else` 的使用
在 MyBatis 动态 SQL 中,可以利用 `<if>` 标签来实现条件判断逻辑。虽然 MyBatis 并未直接提供 `<else>` 标签,但是可以通过组合多个 `<if>` 来模拟 `if-else` 结构。
#### 使用场景示例
假设有一个查询需求,当传入参数不为空时按特定字段过滤;如果该参数为空,则返回全部记录:
```xml
<select id="findUserByCondition" parameterType="map" resultType="com.example.User">
SELECT * FROM users WHERE 1=1
<if test="name != null and name != ''">
AND name LIKE CONCAT('%', #{name}, '%')
</if>
</select>
```
为了达到类似 `if...else` 效果,在第一个条件成立时不执行后续条件,可以在每个 `<if>` 内部设置标志位变量控制流程[^1]。
#### 完整例子展示
下面是一个更复杂的案例,展示了如何通过动态SQL构建带有分支结构的查询语句:
```xml
<sql id="dynamicWhereClause">
<!-- 初始化flag -->
<choose>
<when test="id != null">
AND id = #{id}
</when>
<otherwise>
<if test="email != null and email != ''">
AND email = #{email}
</if>
<if test="age != null">
AND age >= #{age}
</if>
</otherwise>
</choose>
</sql>
<select id="getUserList" parameterType="map" resultMap="BaseResultMap">
SELECT ...
FROM user_table ut
WHERE 1=1
<include refid="dynamicWhereClause"/>
</select>
```
在这个例子中,`<choose><when>...</when><otherwise>...</otherwise></choose>` 组合实现了类似于 Java 中 switch-case 或 if-else-if 的功能。
阅读全文
相关推荐

















