本网站(662p.com)打包出售,且带程序代码数据,662p.com域名,程序内核采用TP框架开发,需要联系扣扣:2360248666 /wx:lianweikj
精品域名一口价出售:1y1m.com(350元) ,6b7b.com(400元) , 5k5j.com(380元) , yayj.com(1800元), jiongzhun.com(1000元) , niuzen.com(2800元) , zennei.com(5000元)
需要联系扣扣:2360248666 /wx:lianweikj
Mybatis的xml中使用if/else标签的具体使用
tezhongbing · 244浏览 · 发布于2022-05-16 +关注

本文主要介绍了Mybatis的xml中使用if/else标签的具体使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

使用if标签进行查询

SELECT
    orderNo,
    adname,
    orderstatus
FROM
    order_A
where
    <if test="order!=null">
        order=#{order}
    </if>
    <if test="title!=null">
        and title=#{title}
    </if>


需要注意的是:如果第一个if的order为null的话 第二值title也为null的话运行会报错,就算第一个if等于null 那么查询语句变成 where and title='哈哈哈' 这样运行的话也会出现错误。 

where标签出场

SELECT
    orderNo,
    adname,
    orderstatus
FROM
    order_A
<where>
    <if test="order!=null">
        order=#{order}
    </if>
    <if test="order!=null">
        and title=#{title}
    </if>
</where>


where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入WHERE子句。而且,若语句的开头为AND或OR,where 元素也会将它们去除。这个只能解决2个值都为空。 

不能解决order值为空但是title值为空时还是会出现语句错误的情况,这个时候我们可以在and 前面用1=1或者true来解决

如:

编辑

或这样

编辑

if/else 使用 choose,when,otherwise 代替

由于Mybatis中没有else标签但是可以通过choose,when,otherwise来使用

SELECT
            orderNo,
            adname,
            orderstatus
FROM
    <choose>
        <when test=" platformtype != null and platformtype.trim() != '' and platformtype == 1">
             `orders_A` as orderTable
        </when>
        <when test=" platformtype != null and platformtype.trim() != '' and platformtype == 2">
             `orders_B` as orderTable
        </when>
        <when test="  platformtype != null and platformtype.trim() != '' and platformtype == 3">
             `orders_C` as orderTable
        </when>
        <otherwise>
             `orders_A` as orderTable
        </otherwise>
    </choose>


翻译一下上面的语句: 

当platformtype 值不为空并且把platformtype 值进行去除空字符串,并且值等于1时
就会把表orders_A进行拼接,如果条件都不符合的话就会走otherwise标签默认拼接orders_A表进行查询

choose,when,otherwise标签有点像Java中的switch 当where的test值满足时会拼接里面的表,otherwise表示其他when标签都不满足时执行拼接


相关推荐

PHP实现部分字符隐藏

沙雕mars · 1324浏览 · 2019-04-28 09:47:56
Java中ArrayList和LinkedList区别

kenrry1992 · 908浏览 · 2019-05-08 21:14:54
Tomcat 下载及安装配置

manongba · 968浏览 · 2019-05-13 21:03:56
JAVA变量介绍

manongba · 961浏览 · 2019-05-13 21:05:52
什么是SpringBoot

iamitnan · 1086浏览 · 2019-05-14 22:20:36
加载中

0评论

评论
分类专栏
小鸟云服务器
扫码进入手机网页