mybatis-24-动态sql常用标签

WHERE标签

  • 应用场景:
    where元素只会在至少有一个子元素的条件返回sql子句的情况下才去插入where子句,而且,若语句开头为and或or,where元素也会将他们去除。
    ”面向百度编程“
    下面来看一下where标签的强大之处
  • BlogMapper8.xml
		 <where>
            <if test="title!=null">
                and title=#{title}
            </if>
            <if test="author!=null">
                and author=#{author}
            </if>
        </where>
  • 情况一:
    where标签后面没有条件,此时会省略where,等同于无条件查询
    在这里插入图片描述

  • 情况二:
    where标签后面跟的第一个条件的and会自动被省略 执行如下
    测试:

map.put("title","2");

执行如下:
在这里插入图片描述

  • 第三种情况
    有一个and,但不是在开头时候,where会执行。
HashMap map = new HashMap<>();
		map.put("title","2");
		map.put("author","1");

在这里插入图片描述

choose

如果第一个满足,不管后面满不满足,都会输出

<select id="queryBlogChoose" parameterType="map" resultType="blog">
        select  * from mybatis.blog
        <where>
            <choose>
                <when test="title!=null">
                    title=#{title}
                </when>
                <when test="author !=null">
                    and author=#{author}
                </when>

                <otherwise>
                    and views=#{views}
                </otherwise>

            </choose>
        </where>
    </select>

Set

自动去除逗号

  • 更新操作
<update id="updateBlog" parameterType="map">
        update mybatis.blog
        <set>
            <if test="title!=null">
                title=#{title},
            </if>
            <if test="author!=null">
                author=#{author}
            </if>
        </set>
        where id=#{id}
    </update>

trim

所谓的动态sql ,本质还是sql , 只是可以在sql层面去执行一些逻辑代码。
没讲到,只是提到trim是choose,set的父类。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值