一、Where
1.1、接口
//查询博客
List<Blog> queryBlogIF(Map map);
1.2、Mapper
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select * from blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
1.3、测试
@Test
public void queryBlogIF(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title" , "Java如此简单");
map.put("author" , "秋风");
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs){
System.out.println(blog);
}
sqlSession.close();
}
1.4、效果
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
二、Choose
2.1、接口
List<Blog> queryBlogChoose(Map map);
2.2、Mapper
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
author = #{author}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
2.3、测试
@Test
public void queryBlogChoose(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("views" , 9999);
List<Blog> blogList = mapper.queryBlogChoose(map);
for (Blog blogs : blogList){
System.out.println(blogs);
}
sqlSession.close();
}
2.4、效果
三、Set
3.1、接口
//更新博客
int updateBlog(Map map);
3.2、Mapper
<update id="updateBlog" parameterType="map">
update blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
where id = #{id}
</update>
3.3、测试
@Test
public void updateBlogSet(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title" , "Java如此简单2");
map.put("author" , "孤冬");
map.put("id","1094fc8af22b425ebca9f138cf550b9d");
mapper.updateBlog(map);
sqlSession.close();
}