Mybatis 动态SQL(三)set标签和update语句
对于查询 SQL 语句包含 where 关键字,如果在进行更新操作的时候,含有 set 关键词,
我们怎么处理呢?
- 编写接口方法
int updateBlog(Map map);
- sql配置文件
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<if test="title!=null">
title=#{title}
</if>
<if test="author!=null">
author=#{author}
</if>
</set>
<where>
id=#{id}
</where>
</update>
- 测试
@Test
public void updateBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap hashMap = new HashMap();
// hashMap.put("views","9999");
hashMap.put("id","b0af9f59259e4946b7f05c4700519a9a");
hashMap.put("title","java如此简单2");
mapper.updateBlog(hashMap);
sqlSession.close();
}
在更新数据的时候,使用< set >标签,使用了set标签会自动帮你补全或删除逗号 里面语句不写逗号就行
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面去执行一些逻辑代码
逻辑 if where set choose when