动态SQL Mybatis中的foreach、if、choose、where、set

动态SQL if和where标签在Mybatis中的语法

如果我们需要拼接where条件,又不希望客户端传递的错误信息,需要更加智能的where标签如果有后面的语句,就自动添加where,并且如果后面的语句开头是and or 它可以自动去掉

<where>
 <if test="  ">
              判断的内容
            </if>
           
            </where>

set标签

set标签重点注意后面的逗号
前几个需要逗号最后一个不需要逗号

set标签如果里面的条件满足,会自动拼接Set标签,后面如果有逗号会自动去处。

<update id="updateBlog" parameterType="map">
        update blog <set>
        <if test="title!=null">title=#{title},</if>
  <if test="author!=null"> author=#{author}</if>

    </set>
           where id=#{id};

    </update>

choose好比switch标签

有时候我们不想用所有的条件语句,而只想从中选择一项,针对这种情况,选择choose元素

<select id="selectBlog" 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>

foreach

sql()子查询where in (1,2,3)
collection输入的参数map中的名字
item遍历出来的每一项
通过item遍历出的参数可以在foreach标签中使用

select * from mybatis.blog;

<foreach collection="ids" item="id" open="and(" close=")" separator="or">
    id=#{id}
</foreach>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值