数据库环境
CREATE TABLE `blog` (
`id` varchar(50) NOT NULL COMMENT '博客id',
`title` varchar(100) NOT NULL COMMENT'博客 标题',
`author`varchar(30) NOT NULL COMMENT '博客作者',
`create_ time` datetime NOT NULL COMMENT '创建时间',
`views` int(30) NOT NULL COMMENT '浏览量'
) ENGINE=InnoDB DEFAULT CHARSET=utf8
常用标签
if
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from mybatis.blog
<!--使用where标签会自动删去第一个满足条件的sql语句中的and和or-->
<where>
<if test="title!=null">
and title = #{title}
</if>
<if test="author!=null">
and author = #{author}
</if>
</where>
</select>
choose(when,otherwise)
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<choose>
<when test="title!=null">
title = #{title}
</when>
<when test="author!=null">
title = #{title}
</when>
<otherwise>
views=#{views}
</otherwise>
</choose>
</where>
</select>
set
set元素会动态前置SET关键字,同时也会删掉无关的逗号
<update id="updateBlog" 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>
trim(where,set)
如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
SQL片段
有时候我们可能会将一些功能的部分抽取出来方便复用
-
使用SQL标签抽取公共部分
<sql id="if-title-author"> <if test="title!=null"> title=#{title}, </if> <if test="author!=null"> author=#{author} </if> </sql>
-
在需要使用的地方使用include标签引用即可
<select id="queryBlogIF" parameterType="map" resultType="blog"> select * from mybatis.blog <where> <include refid="if-title-author"></include> </where> </select>
Foreach
foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符,看它多智能!
提示 你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
open为开始时默认,close为结束时默认,separator为两个item之间的分隔符,collection为遍历的集合名字,item为取到的值名字
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
<where>
<foreach item="item" index="index" collection="list"
open="ID in (" separator="," close=")" nullable="true">
#{item}
</foreach>
</where>
</select>
小结
动态SQL就是拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了