一、根据主键更新(传对象)
1. 接口是:
/* * 根据主键更新 * */ int updateById(SysUser sysUser);
2. xml下:
<update id="updateById"> update sys_user set user_name = #{userName}, user_password = #{userPassword}, user_email = #{userEmail}, user_info = #{userInfo}, head_img = #{headImg ,jdbcType = BLOB}, create_time = #{createTime, jdbcType = TIMESTAMP} where id = #{id} </update>
3. 测试函数:
@Test public void testUpdate(){ SqlSession sqlSession = getSqlSession(); try{ UserMapper userMapper = sqlSession.getMapper(UserMapper.class); SysUser sysUser = userMapper.selectById(1L); Assert.assertEquals("admin_test1",sysUser.getUserName()); sysUser.setUserName("admin"); sysUser.setUserEmail("test@com.example"); sysUser.setUserInfo("admin_test info"); int result = userMapper.updateById(sysUser); System.out.println(result); Assert.assertNotEquals(1,result); sysUser = userMapper.selectById(1L); Assert.assertEquals("admin",sysUser.getUserName()); }finally { sqlSession.commit(); sqlSession.close(); } }
二、通过Map更新列(传Map)
1. 接口如下:
/* * 通过Map更新列 * */ int updateByMap(Map<String, Object> map);
2. xml中:
<update id="updateByMap"> update sys_user set <foreach collection="_parameter" item="val" index="key" separator=","> ${key} = #{val} </foreach> where id = #{id} </update>
注:这里没有通过@ Param 注解指定参数名,因而 MyBati 在内部的上下文中使用了默认值_parameter 作为该参数的 key ,所以在 XML 使用了_parameter
item:变量名,值为从法代对象中取出的每一个值。
index:这个值为 Map key (键值)
3. 测试函数如下:
@Test public void testUpdateByMap(){ SqlSession sqlSession = getSqlSession(); try { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); Map<String, Object> map = new HashMap<String, Object>(); map.put("id" , 1L); map.put("user_email","test@ccc.tk"); map.put("user_password", "12345678"); userMapper.updateByMap(map); SysUser user = userMapper.selectById(1L); Assert.assertEquals("test@ccc.tk",user.getUserEmail()); }finally { sqlSession.close(); } }
至此,结束。