SQL Update時參數判空:傳入參數為空時不更新對應字段,不為空時才更新



核心思想:
在原始SQL中嵌入if語句,類似於XML格式,如下
@Update("<script>update user set " +
"<if test = 'username != null'> username = #{username} ,</if>" +
"<if test = 'password != null'> password = #{password} ,</if>" +
"<if test = 'realName != null'> real_name = #{realName},</if>" +
"<if test = 'identitySign != null'> identity_sign= #{identitySign},</if>" +
"<if test = 'collegeName != null'>college_name= #{collegeName},</if>" +
"<if test = 'majorName != null'> major_name= #{majorName},</if>" +
"<if test = 'className != null'> class_name= #{className},</if>" +
"<if test = 'email != null'> email= #{email},</if>" +
"<if test = 'phone != null'> phone= #{phone},</if>" +
"<if test = 'operateIp != null'> operate_ip= #{operateIp} </if>" +
"where id = #{id} and del_flag = 0 </script>" )
void updateUser(User user);

傳入的User對象,可能只包含更新某些字段,那么其它沒有傳入的字段意味着不更新。
如果不在SQL中判空,也不再代碼中增加判空,那么沒傳進來的數據會被更新成NULL。



參考 https://blog.csdn.net/weixin_41637378/article/details/79397254


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM