在 MyBatis 中,可以使用 <if>
標簽來判斷某個屬性是否為 null,然后根據情況決定是否插入該屬性值。
例如,假設有一個用戶實體類 User,其中有兩個屬性 id 和 name。如果 name 可能為 null,可以在對應的 SQL 映射文件中這樣寫:
<insert id="insertUser" parameterType="User">
INSERT INTO user (id, name)
VALUES (#{id},
<if test="name != null">
#{name}
</if>
)
</insert>
這樣在插入數據時,如果 name 不為 null,則會插入 name 的值;如果 name 為 null,則不會插入 name 屬性,保持數據庫表中的字段值為 null。
另外,還可以使用 <choose>
標簽和 <when>
標簽來實現類似的功能:
<insert id="insertUser" parameterType="User">
INSERT INTO user (id, name)
VALUES (#{id},
<choose>
<when test="name != null">
#{name}
</when>
<otherwise>
NULL
</otherwise>
</choose>
)
</insert>
通過以上方式,可以靈活處理插入數據時的 null 值。