Mybatis -> 动态SQL之trim,set

set:

    <update id="setUpdate">
        update blog
        /*set里面就都是些赋值什么,就不要搞where那种标签进去了,会报错的*/
        /*set中加choose要加默认的otherwise,不然update没set也没意义了 且choose只会执行一个条件,所以,也不用加了*/
        <set>
            <choose>
                <when test="title != null">
                    title= #{title},
                </when>
                <otherwise>
                    views=#{views}
                </otherwise>
            </choose>
        </set>
        /*update的where是必须加的 不然就没有意义了*/
        where author=#{author}
    </update>
    <update id="setUpdate">
        update blog
        /*set的if标签必须记得加,逗号 否则会报错,因为可能会满足多个条件,可以多加逗号但是不能少加逗号*/
        <set>
            <if test="title !=null">
                title=#{title},
            </if>
            <if test="id != null">
                id =#{id},
            </if>
        </set>
        where author=#{author}
    </update>

官方的解释

用于动态更新语句的类似解决方案叫做 set。set 元素可以用于动态包含需要更新的列,忽略其它不更新的列。比如:

<update id="updateAuthorIfNecessary">
  update Author
    <set>
      <if test="username != null">username=#{username},</if>
      <if test="password != null">password=#{password},</if>
      <if test="email != null">email=#{email},</if>
      <if test="bio != null">bio=#{bio}</if>
    </set>
  where id=#{id}
</update>

这个例子中,set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。

来看看与 set 元素等价的自定义 trim 元素吧:

<trim prefix="SET" suffixOverrides=",">
  ...
</trim>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值