MyBatis中update用法
本篇内容
- update标签的基本用法
实践-更新一条记录
mapper中接口
/**
* 根据主键更新
* @param user 用户记录
* @return 执行得sql影响得行数
*/
int updateById(SysUser user);
xml,update标签里,在createTime和headImg两个属性上也可以添加jdbcType的类型
<!--通过主键修改数据-->
<update id="updateById">
update mybatis.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},
</set>
where id = #{id}
</update>
测试方法,查询一条记录后修改用户名和用户邮箱,看是否更新成功
public void testUpdateById(){
SqlSession sqlSession = getSqlSession();
try {
SysUserMapper mapper = sqlSession.getMapper(SysUserMapper.class);
//获取数据库中一条记录进行修改
SysUser user = mapper.queryById(1L);
Assert.assertEquals("admin",user.getUserName());
LOGGER.info("用户信息:{}",user.toString());
// 修改用户名
user.setUserName("admin_test");
user.setUserEmail("[email protected]");
//更新数据,update方法返回值是执行sql影响的行数
int result = mapper.updateById(user);
Assert.assertEquals(1,result);
//查看修改后的数据
SysUser sysUser = mapper.queryById(1L);
LOGGER.info("修改后的用户信息:{}",sysUser.toString());
Assert.assertEquals("admin_test",sysUser.getUserName());
} finally {
//为了不影响其他测试,这里进行回滚
//由于默认的sqlSessionFactory.openSession()是不自动提交的
//因此不手动执行commit也不会提交到数据库
sqlSession.rollback();
//关闭sqlSession
sqlSession.close();
}
}
执行结果,
==> Preparing: select id, user_name, user_password, user_email, user_info, head_img, create_time from mybatis.sys_user where id = ?
==> Parameters: 1(Long)
<== Columns: id, user_name, user_password, user_email, user_info, head_img, create_time
<== Row: 1, admin, 123456, admin@mybatis.tk, <<BLOB>>, <<BLOB>>, 2021-01-28 21:57:32.0
<== Total: 1
用户信息:SysUser{id=1, userName='admin', userPassword='123456', userEmail='[email protected]', userInfo='管理员', headImg=null, createTime=Thu Jan 28 21:57:32 CST 2021}
==> Preparing: update mybatis.sys_user SET user_name = ?, user_password = ?, user_email = ?, user_info = ?, create_time = ? where id = ?
==> Parameters: admin_test(String), 123456(String), test@mybatis.tk(String), 管理员(String), 2021-01-28 21:57:32.0(Timestamp), 1(Long)
<== Updates: 1
==> Preparing: select id, user_name, user_password, user_email, user_info, head_img, create_time from mybatis.sys_user where id = ?
==> Parameters: 1(Long)
<== Columns: id, user_name, user_password, user_email, user_info, head_img, create_time
<== Row: 1, admin_test, 123456, test@mybatis.tk, <<BLOB>>, <<BLOB>>, 2021-01-28 21:57:32.0
<== Total: 1
修改后的用户信息:SysUser{id=1, userName='admin_test', userPassword='123456', userEmail='[email protected]', userInfo='管理员', headImg=null, createTime=Thu Jan 28 21:57:32 CST 2021}