MyBatis 最强大的特性之一是它的动态语句功能。如果你以前使用 JDBC 或者类似的框架,你就会明白把 SQL 语句条件连接在一起是多么的痛苦,一点都不能疏忽空格和逗号等。动态语句完全能解决这些烦恼。
■ 动态SQL分类
1. if
2. choose (when, otherwise)
3. trim (where, set)
4. foreach
动态SQL标签的使用和EL表达式有些类似
■ 案例
假设我们这里有一个博客表(博客id,博客titile,作者id),即:blog(id,title,author_id)
1. if
实现通过title查找博客,博客可能为空
id 通过id找到相应的SQL语句
parameterType 传入参数类型
resutType 返回参数类型
<select id="findByTitle" parameterType="blog" resultType="blog" >
select * from blog where 1=1
<if test="title!=null">
and title like #{title}
</if>
</select>
预编译
test设置条件,当满足条件时,附加上后面的代码
当不满足条件时,查询全部blog信息
2. choose
使用choose关键字来实现上述功能
<select id="findByTitle" parameterType="blog" resultType="blog" >
select * from blog where 1=1
<choose>
<when test="title!=null">
and title like #{title}
</when>
</choose>
</select>
预编译
同理,条件满足时,拼接SQL语句
不满足时,不拼接
3. trim
trim的功能是非常强大的,可代替上面所述两种方式
prefix 前缀
prefixOverrides 后缀,满足条件时添加的关键字
<select id="findByTitle" parameterType="blog" resultType="blog">
select * from blog
<trim prefix="where" prefixOverrides="and/or">
<if test="title!=null">
title like #{title}
</if>
</trim>
</select>
预编译
当满足条件时
当不满足条件时
4. where
当title不为空时,会自动拼接上where子句;当title为空时,不会拼接where子句
<select id="findByTitle" parameterType="blog" resultType="blog">
select * from blog
<where>
<if test="title!=null">
and title like #{title}
</if>
</where>
</select>
5. set
对blog表进行修改
<update id="updateBlog" parameterType="blog">
update blog
<set>
<if test="title!=null">title=#{title},</if>
<if test="author_id!=null">author_id=#{author_id},</if>
</set>
where id = #{id}
</update>
当满足条件时,不管是一个还是两个,都会自动拼接
当不满足条件时,还是会自动拼接上set子句,不过会给一个默认的值0,如果不拼接上set,update语句首先就是不完整的
6. foreach
查找id属于某个范围的blog,传入的值是list类型,foreach用于遍历传入的list
collection 指定的集合,这里为“list”
open/close 开始和结束字符,这里以左括号开始,右括号结束
separator 两个迭代器之间加入的分隔符
<select id="findByIds" resultType="blog">
select * from blog where id in
<foreach collection="list" item="item" open="(" close=")" separator=",">
#{item}
</foreach>
</select>
效果显示