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>