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

你猜 阅读:804 2021-03-18 18:16:48 评论:0

案例一: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
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号