mybatis if..else

本文详细解析了MyBatis中的if-else语法,通过具体案例展示了如何使用<choose>、<when>和<otherwise>标签进行条件判断,以及在SQL语句中正确使用转义符的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.mybatis中if-else的语法

<choose>
    <when test="">
        //...
    </when>
    <otherwise>
        //...
    </otherwise>
</choose>

2举例:

/**
* 需求: 1 当选择问答标签,即不为空时, 可实现拖动排序,且按时间顺序排序
* 	   2 若没有选择问答标签,则按时间倒叙排序
* / 
<select id="getQuestionAnswerList" resultType="QuestionAnswerDto">
        SELECT id, question_type AS questionType, question, answer, picture_url AS pictureUrl, page_view AS pageView,
        resolved_count AS resolvedCount, unresolved_count AS unresolvedCount, priority, enable, created, modified
        FROM t_question_answer
        WHERE enable = 1
        <choose>
            <when test="questionType != null and questionType &gt;0 and questionType &lt;100" >
                  AND question_type = #{questionType}
                  ORDER BY priority ASC, created ASC
            </when>
            <otherwise>
                ORDER BY created DESC
            </otherwise>
        </choose>
        <if test="start >= 0 and size >0 ">
            limit #{start}, #{size}
        </if>

</select>

(1) 之前, 在sql中显示如下图错误
在这里插入图片描述
(2)原因

	在if-else 比较时, 用了> 和 <, 但是在mybatis中不能识别小于号<,所以报错
	在mybatis中最好用转义符来表示

(3) 在mybatis中的转义符

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值