动态SQL学习笔记
什么是动态SQL?
我的理解:动态SQL就是通过不同的判定条件来生成或拼接不同的SQL语句来达到完美想要实现的功能。
官网:
动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。
使用动态 SQL 并非一件易事,但借助可用于任何 SQL 映射语句中的强大的动态 SQL 语言,MyBatis
显著地提升了这一特性的易用性。如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
动态SQL元素
where
where元素只会在你需要使用where的SQL语句时为你拼接where,而且会帮你判断AND是否去掉。所以你不必担心自己写的SQL语句拼接时AND的位置。
例:
<select id="queryBlogIf" resultType="Blog" parameterType="map">
select * from mybatis.blog
<where>
<if test="title!=null">
AND title=#{title}
</if>
<if test="author!=null">
AND author=#{author}
</if>
</where>
</select>
if
if元素可以通过判断用户的传参来决定拼接哪一段SQL语句。但仅仅是拼接,它不会判断你语句中and或者","。
<select id="queryBlogIf" resultType="Blog" parameterType="map">
select * from mybatis.blog where 1=1
<if test="title!=null">
AND title=#{title}
</if>
<if test="author!=null">
AND author=#{author}
</if>
</select>
choose
choose元素的作用于java中switch类似,选择一条语句拼接.
<select id="queryBlogChoose" parameterType="map" resultType="Blog">
SELECT * FROM mybatis.blog
<where>
<choose>
<when test="title!=null">
title=#{title}
</when>
<when test="author!=null">
author=#{author}
</when>
<otherwise>
views>#{views}
</otherwise>
</choose>
</where>
</select>
set
set 元素可以用于动态包含需要更新的列,忽略其它不更新的列。set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。
<update id="upadate" parameterType="map">
UPDATE mybatis.blog
<set>
<if test="title!=null">
title=#{title},
</if>
<if test="author!=null">
author=#{author},
</if>
</set>
where id=#{id}
</update>
SQL片段
有时候,我们可能需要将一些功能的部分抽取出来,方便复用!
- 使用SQL标签抽取公共部分
<sql id="if-title-author">
<if test="title!=null">
AND title=#{title}
</if>
<if test="author!=null">
AND author=#{author}
</if>
</sql>
2.在需要使用的地方用include标签引用
<select id="queryBlogIf" resultType="Blog" parameterType="map">
select * from mybatis.blog
<where>
<include refid="if-title-author"/>
</where>
</select>
注意事项:
- 最好基于单表来定义SQL片段
- SQL片段中不要存在where,set标签
foreach
<select id="queryForeach" parameterType="map" resultType="Blog">
SELECT * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator=" or ">
id = #{id}
</foreach>
</where>
</select>
foreach标签需要传入一个集合参数,然后通过遍历这个集合中有的数据来实现SQL拼接
foreach标签的属性:
- open:定义你接下来需要拼接的SQL语句的开端。
- close:定义你接下来需要拼接的SQL语句的结尾。
- separator:定义你接下来要拼接每个字段的分割符号。
- collection:这个属性中传入你需要遍历的集合。
- item:这个属性是从这个集合中遍历出来的每一项。
- foreach标签中写你需要在open后,close前拼接的字段
根据上述定义,假设传入的集合ids中有3个数据,{1,2,3}。
那foreach拼接的SQL语句为:
and (id = 1 or id = 2 or id = 3)