set - 更新語句
當 update 語句中沒有使用 if 標籤時,如果有一個參數為 null,都會導致錯誤。
當在 update 語句中使用if標籤時,如果前面的if沒有執行,則或導致逗號多餘錯誤。使用set標籤可以將動態的配置 SET 關鍵字,並剔除追加到條件末尾的任何不相關的逗號。使用 if+set 標籤修改後,如果某項為 null 則不進行更新,而是保持資料庫原值。如下示例:
<!-- if/set(判斷參數) - 將實體 User類不為空的屬性更新 -->
<update id="updateUser_if_set" parameterType="com.pojo.User">
UPDATE user
<set>
<if test="username!= null and username != '' ">
username = #{username},
</if>
<if test="sex!= null and sex!= '' ">
sex = #{sex},
</if>
<if test="birthday != null ">
birthday = #{birthday},
</if>
</set>
WHERE user_id = #{userid};
</update>
再看看下麵的一個示例:
<update id="dynamicSetTest" parameterType="Blog">
update t_blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="content != null">
content = #{content},
</if>
<if test="owner != null">
owner = #{owner}
</if>
</set>
where id = #{id}
</update>
set 標籤元素主要是用在更新操作的時候,它的主要功能和 where 標籤元素其實是差不多的,主要是在包含的語句前輸出一個 set,然後如果包含的語句是以逗號結束的話將會把該逗號忽略,如果 set 包含的內容為空的話則會出錯。有了 set 元素就可以動態的更新那些修改了的字段。
上一篇:
MyBatis where標籤語句
下一篇:
Mybatis trim標籤
