MyBatis插入數(shù)據(jù)時(shí)如何處理null值

小樊
118
2024-08-21 13:56:28

在 MyBatis 中,可以使用 <if> 標(biāo)簽來(lái)判斷某個(gè)屬性是否為 null,然后根據(jù)情況決定是否插入該屬性值。

例如,假設(shè)有一個(gè)用戶實(shí)體類 User,其中有兩個(gè)屬性 id 和 name。如果 name 可能為 null,可以在對(duì)應(yīng)的 SQL 映射文件中這樣寫:

<insert id="insertUser" parameterType="User">
    INSERT INTO user (id, name)
    VALUES (#{id}, 
            <if test="name != null">
                #{name}
            </if>
           )
</insert>

這樣在插入數(shù)據(jù)時(shí),如果 name 不為 null,則會(huì)插入 name 的值;如果 name 為 null,則不會(huì)插入 name 屬性,保持?jǐn)?shù)據(jù)庫(kù)表中的字段值為 null。

另外,還可以使用 <choose> 標(biāo)簽和 <when> 標(biāo)簽來(lái)實(shí)現(xiàn)類似的功能:

<insert id="insertUser" parameterType="User">
    INSERT INTO user (id, name)
    VALUES (#{id},
            <choose>
                <when test="name != null">
                    #{name}
                </when>
                <otherwise>
                    NULL
                </otherwise>
            </choose>
           )
</insert>

通過(guò)以上方式,可以靈活處理插入數(shù)據(jù)時(shí)的 null 值。

0