第十二章、动态SQL
什么是动态SQL
动态SQL就是根据不同的条件生成不同的SQL语句
1 如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器, 2 你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中, 3 需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式, 4 MyBatis 3 替换了之前的大部分元素,大大精简了元素种类, 5 现在要学习的元素种类比原来的一半还要少。 6 if 7 choose (when, otherwise) 8 trim (where, set) 9 foreach
搭建环境
1 CREATE TABLE `blog`( 2 `id` VARCHAR(50) NOT NULL COMMENT '博客id', 3 `title` VARCHAR(100) NOT NULL COMMENT '博客标题', 4 `author` VARCHAR(30) NOT NULL COMMENT '博客作者', 5 `create_time` DATETIME NOT NULL COMMENT '创建时间', 6 `views` INT(30) NOT NULL COMMENT '浏览量' 7 )ENGINE=INNODB DEFAULT CHARSET=utf8
IF
1 <select id="queryBlog" resultType="blog" parameterType="map"> 2 select * from blog 3 where 1=1 4 <if test="title != null"> 5 and title = #{title} 6 </if> 7 <if test="author != null"> 8 and author = #{author} 9 </if> 10 </select>
choose (when, otherwise)
1 <select id="queryBlogChoose" resultType="blog" parameterType="map"> 2 select * from blog 3 <where> 4 <choose> 5 <when test="title != null"> 6 title = #{title} 7 </when> 8 <when test="author != null"> 9 and author = #{author} 10 </when> 11 <otherwise> 12 and views = #{views} 13 </otherwise> 14 </choose> 15 </where> 16 </select>
trim (where, set)
1 <select id="queryBlog" resultType="blog" parameterType="map"> 2 select * from blog 3 <where> 4 <if test="title != null"> 5 title = #{title} 6 </if> 7 <if test="author != null"> 8 and author = #{author} 9 </if> 10 </where> 11 </select>
1 <update id="updateBlog" parameterType="map"> 2 update blog 3 <set> 4 <if test="title != null"> 5 title = #{title}, 6 </if> 7 <if test="author"> 8 author = #{author} 9 </if> 10 </set> 11 where id = #{id} 12 </update> 13
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码
SQL片段
有的时候,我们可能会将一些功能的部分抽取出来,方便复用
-
使用SQL标签抽取公共部分
1 <sql id="if-title-authou"> 2 <if test="title != null"> 3 title = #{title}, 4 </if> 5 <if test="author"> 6 author = #{author} 7 </if> 8 </sql>
-
在需要使用的地方使用Include标签引用
1 <update id="updateBlog" parameterType="map"> 2 update blog 3 <set> 4 <include refid="if-title-authou"></include> 5 </set> 6 where id = #{id} 7 </update>
注意事项:
-
-
不要存在where标签
Foreach
1 <select id="queryBlogForeach" parameterType="map" resultType="blog"> 2 select * from blog 3 <where> 4 <foreach collection="ids" item="id" open="id in (" close=")" separator=","> 5 #{id} 6 </foreach> 7 </where> 8 </select>
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
建议

浙公网安备 33010602011771号