Mybatis-動態sql之set
阿新 • • 發佈:2020-12-23
Mybatis-動態sql之set
例如我們要對資料庫中一張user表的資料進行更新時,有的屬性改變,有的屬性不改變,這時實體類中可能會出現沒有值的屬性,針對這種情況,可以通過mybatis的set標籤進行動態更新資料,該屬性有值就更新,沒有值就不做處理。
<update id="updateIf" parameterType="user"> UPDATE `user` <set> <if test="username != null"> username = #{username}, </if> <if test="birthday != null"> birthday = #{birthday}, </if> <if test="sex !=null"> sex = #{sex}, </if> <if test="address !=null"> address = #{address}, </if> </set> WHERE id = #{id} </update>
set標籤在更新的時候會自動加上set關鍵字,並且去掉最後一個條件後面的逗號。