信息发布→ 登录 注册 退出

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

发布时间:2026-01-11

点击量:
目录
  • if-else及if嵌套使用方式
    • 案例一:if-else
    • 案例二:if嵌套
  • mybatis if-else写法

    if-else及if嵌套使用方式

    案例一:if-else

    在使用mybatis mapper 动态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>

    mybatis if-else写法

    mybaits中没有else要用chose when otherwise代替

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

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

    在线客服
    服务热线

    服务热线

    4008888355

    微信咨询
    二维码
    返回顶部
    ×二维码

    截屏,微信识别二维码

    打开微信

    微信号已复制,请打开微信添加咨询详情!