定义:
动态SQL就是指根据不同的条件生成不同的SQL语句
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
动态SQL之if
使用动态 SQL 最常见情景是根据条件包含 where 子句的一部分
//如果传入的值为null,或只有title或只有author,会产生不同的结果
<select id="queryBlogIF" parameterType="map" resultType="Blog" resultMap="blog">
select * from mybatis.blog where 1=1
<if test="title!=null">
and title=#{title}
</if>
<if test="author!=null">
and author =#{author}
</if>
</select>
动态SQL之where
where标签
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
问题:
where后没有条件直接接了[and...]显然是不对的
SELECT * FROM BLOG
WHERE
AND title like ‘someTitle’
这个查询也会失败。这个问题不能简单地用条件元素来解决。这个问题是如此的难以解决,以至于解决过的人不会再想碰到这种问题。
MyBatis 有一个简单且适合大多数场景的解决办法。而在其他场景中,可以对其进行自定义以符合需求。而这,只需要一处简单的改动:
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</where>
</select>
动态SQL之choose
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
<select id="queryBlogIF" parameterType="map" resultType="Blog" resultMap="blog">
select * from mybatis.blog
<where>
<choose>
<when test="title!=null">
and title=#{title}
</when>
<otherwise>
and views=#{views}
</otherwise>
</choose>
</where>
</select>
SQL片段
有的时候,我们可能会将一些功能的部分抽取出来,方便复用
1.使用SQL标签抽取公共部分
sql id="if-title-author">
<if test="title!=null">
title=#{title},
</if>
<if test="author!=null">
author=#{author},
</if>
</sql>
2.使用include标签引用
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<include refid="if-title-author"></include>
</set>
<where>
id=#{id}
</where>
</update>