mybatis中的if-else使用及if嵌套使用

案例一:if-else

在使用mybatismapper动态sql时,不免会出现if-else的使用,但是好像又没有这种语法,提供的是choose标签代替if-else

例如:

select * from t_stu t
<where>
    <choose>
        <when test="query == 0">
            and t.status = 1 
        </when>
        <otherwise>
                and t.status  NOT IN (9,5)
        </otherwise>
    </choose>
    and t.delete_status = 1
</where>

也可以用多个if判断实现:

select * from t_stu t
<where>
    <if test="query == 0">
        and t.status = 1 
    </if>
    <if test="query != 0">
        and t.status  NOT IN (9,5)
    </if>
    and t.delete_status = 1
</where>

案例二:if嵌套

在实际编码过程中会有一些判断条件会一直重复使用,一直写在if标签中写的代码会特长,而且臃肿

select * from t_stu t
<where>
    <if test="query == 0 and type = 1">
        and t.type = 'we' and t.delete = 1
    </if>
    <if test="query == 0 and type = 2">
        and t.type = 'wq' and t.delete = 1
    </if>
    <if test="query == 0 and type = 3">
        and t.type = 'wr' and t.delete = 1
    </if>
</where>

变现后:

select * from t_stu t
<where>
    <if test="query == 0">
        <if test="type = 1">
            and t.type = 'we'
        </if>
         <if test="type = 2">
            and t.type = 'wq'
        </if>
        <if test="type = 3">
            and t.type = 'wr'
        </if>
    </if>
    and t.delete = 1
</where>
  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis的if-else语句可以使用<choose>...<when>...<otherwise>...</choose>来表示。在<choose>标签,可以使用多个<when>标签来表示多个条件判断,最后使用<otherwise>标签来表示其他情况。 举个例子,如果我们在一个查询语句需要根据不同的条件来动态生成不同的SQL语句,可以使用if-else来实现。在<select>标签的SQL语句使用<choose>标签包裹条件判断的逻辑。每个条件判断使用<when>标签表示,例如当xxx不为空时,使用<when>语句来拼接SQL语句的条件;当xxx为空时,使用<otherwise>语句来拼接SQL语句的条件。 另外还有一个示例是在插入语句使用if-else语句。在<insert>标签使用<foreach>循环来遍历列表,并使用<trim>标签来拼接SQL语句的字段和对应的值。在<choose>标签使用<when>语句来判断字段的值是否为空,如果不为空,则使用字段的值,如果为空,则使用指定的默认值。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [mybatis xml mapper 文件 if-else 写法](https://blog.csdn.net/aotun7642/article/details/102437909)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值