<!--需求1: 根据作者名字和博客名字来查询博客! 如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询 select * from blog where title = #{title} and author = #{author} --> <selectid="queryBlogIf"parameterType="map"resultType="blog"> select * from blog where <iftest="title != null"> title = #{title} </if> <iftest="author != null"> and author = #{author} </if> </select>
这样写我们可以看到,如果 author 等于 null,那么查询语句为 select * from user where title=#{title},但是如果title为空呢?那么查询语句为 select * from user where and author=#{author},这是错误的 SQL 语句!如何解决呢?请看下面的 where 语句!
where语句
修改上面的SQL语句:
1 2 3 4 5 6 7 8 9 10 11
<selectid="queryBlogIf"parameterType="map"resultType="blog"> select * from blog <where> <iftest="title != null"> title = #{title} </if> <iftest="author != null"> and author = #{author} </if> </where> </select>
将数据库中前三个数据的id修改为1,2,3;需求:我们需要查询 blog 表中 id 分别为1,2,3的博客信息,即遍历前三个数据项,对应接口queryBlogForeach。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
<selectid="queryBlogForeach"parameterType="map"resultType="blog"> select * from blog <where> <!-- collection:指定输入对象中的集合属性 item:每次遍历生成的对象 open:开始遍历时的拼接字符串 close:结束时拼接的字符串 separator:遍历对象之间需要拼接的字符串 select * from blog where 1=1 and (id=1 or id=2 or id=3) --> <foreachcollection="ids"item="id"open="and ("close=")"separator="or"> id=#{id} </foreach> </where> </select>
<sqlid="if-title-author"> <iftest="title != null"> title = #{title} </if> <iftest="author != null"> and author = #{author} </if> </sql>
<selectid="queryBlog"parameterType="map"resultType="Blog"> select * from mybatis.blog <where> <includerefid="if-title-author"></include> </where> </select>
<selectid="queryBlogChoose"parameterType="map"resultType="Blog"> select * from mybatis.blog <where> <choose> <whentest="title != null"> title = #{title} </when> <whentest="author != null"> and author = #{author} </when> <otherwise> and views = #{views} </otherwise> </choose> </where> </select>
<updateid="updateBlog"parameterType="map"> update mybatis.blog <set> <iftest="title != null"> title = #{title}, </if> <iftest="author != null"> author = #{author} </if> </set> where id = #{id} </update>
<!-- select * from blog where 1=1 and ( id=1 or id=2 or id=3 ); 传入的Collection是由map提供的 --> <selectid="queryBlogForeach"parameterType="map"resultType="Blog"> select * from mybatis.blog <where> <foreachcollection="ids"item="id"open="and ("close=")"separator="or"> id = #{id} </foreach> </where> </select>