假设需求:只更新有变化的字段,不能将原来有值但没有发生变化的字段更新为空或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的用户邮箱已修改