當(dāng) update 語句中沒有使用 if 標(biāo)簽時,如果有一個參數(shù)為 null,都會導(dǎo)致錯誤。
當(dāng)在 update 語句中使用if標(biāo)簽時,如果前面的if沒有執(zhí)行,則或?qū)е露禾柖嘤噱e誤。使用set標(biāo)簽可以將動態(tài)的配置 SET 關(guān)鍵字,并剔除追加到條件末尾的任何不相關(guān)的逗號。使用 if+set 標(biāo)簽修改后,如果某項(xiàng)為 null 則不進(jìn)行更新,而是保持?jǐn)?shù)據(jù)庫原值。如下示例:
<!-- if/set(判斷參數(shù)) - 將實(shí)體 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 標(biāo)簽元素主要是用在更新操作的時候,它的主要功能和 where 標(biāo)簽元素其實(shí)是差不多的,主要是在包含的語句前輸出一個 set,然后如果包含的語句是以逗號結(jié)束的話將會把該逗號忽略,如果 set 包含的內(nèi)容為空的話則會出錯。有了 set 元素就可以動態(tài)的更新那些修改了的字段。