鍍金池/ 教程/ Java/ Mybatis set標(biāo)簽
Mybatis表關(guān)聯(lián)多對(duì)一
MyBatis打印輸出SQL語(yǔ)句
Mybatis表關(guān)聯(lián)一對(duì)多
mybaits if標(biāo)簽語(yǔ)句
MyBatis整合Spring MVC
MyBatis動(dòng)態(tài)SQL語(yǔ)句
MyBatis教程
MyBatis choose(when, otherwise)標(biāo)簽
Mybatis與Spring集成
MyBatis分頁(yè)
MyBatis SqlSessionDaoSupport實(shí)例
MyBatis where標(biāo)簽語(yǔ)句
Mybatis增刪改查(CURD)
Mybatis接口注解
Mybatis trim標(biāo)簽
Mybatis set標(biāo)簽
Mybatis 多對(duì)多
MyBatis環(huán)境配置及入門(mén)

Mybatis set標(biāo)簽

set - 更新語(yǔ)句

當(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)的更新那些修改了的字段。