服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - mybatis中的if-else及if嵌套使用方式

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

2022-10-18 14:43小小猴冲刺 Java教程

这篇文章主要介绍了mybatis中的if-else及if嵌套使用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

if-else及if嵌套使用方式

案例一:if-else

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

例如:

?
1
2
3
4
5
6
7
8
9
10
11
12
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判断实现:

?
1
2
3
4
5
6
7
8
9
10
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标签中写的代码会特长,而且臃肿

?
1
2
3
4
5
6
7
8
9
10
11
12
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>

变现后:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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代替

?
1
2
3
4
5
6
7
8
<choose>
    <when test="">
        //...
    </when>
    <otherwise>
        //...
    </otherwise>
</choose>

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

原文链接:https://blog.csdn.net/qq_43040552/article/details/104747240

延伸 · 阅读

精彩推荐