MyBatis--動態SQL(在updae更新列中使用if)


  假設需求:只更新有變化的字段,不能將原來有值但沒有發生變化的字段更新為空或null。

在UserMapper接口中增加對應的接口方法,代碼如下:

1  /**
2      * 根據主鍵更新
3      * @param sysUser
4      * @return
5      */
6     int updateById(SysUser sysUser);

XML文件SQL

 1 <update id="updateById">
 2         update sys_user
 3         set 
 4         <if test="userName != null and userName !=''">
 5             user_name =#{userName},
 6         </if>
 7         <if test="userPassword != null and userPassword != ''">
 8             user_password =#{userPassword},
 9         </if>
10         <if test="userEmail != null and userEmail != ''">
11             user_email =#{userEmail},
12         </if>
13         <if test="userInfo != null and userInfo != ''">
14             user_info =#{userInfo},
15         </if>
16         <if test="headImg != null">
17             head_img =#{headImg},
18         </if>
19         <if test="createTime != null">
20             create_time =#{createTime},
21         </if>
22             id =#{id}
23         where id =#{id}
24     </update>

  這里需要結合業務層的邏輯判斷,確保最終產生的SQL語句沒有語法錯誤。這里需要注意的有兩點:第一是每個if元素里面SQL語句后面的逗號;第二點就是where關鍵字前面的id =#{id}這個條件。

  第一種情況:

 

   第二種情況:

 

 

測試類新增測試方法

 1   @Test
 2     void test3(){
 3         //創建一個新的SysUser對象
 4         SysUser user = new SysUser();
 5         //更新id = 1005L的用戶
 6          user.setId(1005L);
 7          //更新郵箱
 8          user.setUserEmail("test@3173.tk");
 9          //result執行的是SQL影響的行數
10          int result = userMapper.updateById(user);
11          //根據當前id查詢修改后的數據
12          user = userMapper.selectById(1005L);
13         System.out.println(user);
14         }

右鍵運行test3()方法后,如下圖,可以看到id=1005的用戶郵箱已修改

 

 

 

 

  

  

 


免責聲明!

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



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