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