Mybatis-动态SQL(2)
1. where标签
在上一篇中使用动态SQL-IF的时候查询语句是:
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select * from blog where 1=1
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>
这里的where1=1是没有道理的,这样做只是为了使SQL语句符合语法;Mybatis对此提供了相应的解决方法:where标签
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select * from blog
<where>
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除;
类似的还有set标签:(例如)
<update id="updateAuthorIfNecessary">
update Author
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="bio != null">bio=#{bio}</if>
</set>
where id=#{id}
</update>
set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号;
2. choose标签
-
接口
List<Blog> queryBlogCHOOSE(Map<String, Object> map);
-
Mapper.xml
<select id="queryBlogCHOOSE" parameterType="map" resultType="Blog"> select * from blog <where> <choose> <when test="title != null"> and title = #{title} </when> <when test="author != null"> and author = #{author} </when> <otherwise> and views = #{views} </otherwise> </choose> </where> </select>
这里通过where标签会将where后的第一个语句中的and去掉;
-
测试
@Test public void test() { SqlSession sqlSession = MybatisUtils.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); HashMap map = new HashMap<String, Object>(); map.put("title", "Java"); map.put("author", "kangkang"); List<Blog> blogs = mapper.queryBlogCHOOSE(map); for (Blog blog : blogs) { System.out.println(blog); } sqlSession.close(); }
虽然说没有符合数据库中没有符合author为kangkang的item,但是title为Java的item还是会被查询出来;
与IF不同的是:if标签是符合条件的多个语句的拼接,choose是选择第一个符合条件的语句作为约束(类似于switch)
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码;