mybatis的强大特性只有的动态sql,他的动态sql主要依赖于他的元素,该文章主要用来记录自己学习元素,方便日后复习。
if
<if test="title != null and title != ''">
AND title like #{title}
</if>
if提供了一种可选的查找文本功能。如果没有传入“title”,那么所有处于“ACTIVE”状态的BLOG都会返回;反之若传入了“title”,那么就会对“title”一列进行模糊查找并返回 BLOG 结果(细心的读者可能会发现,“title”参数值是可以包含一些掩码或通配符的)。
choose, when, otherwise
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
trim, where, set
where等价的自定义trim元素
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
set等价的自定义trim元素
<trim prefix="SET" suffixOverrides=",">
...
</trim>
trim有四个属性:prefix,prefixOverrides,suffix,suffixOverrides
prefix,suffix 表示在trim标签包裹的部分的前面或者后面添加内容
prefixOverrides,suffixOverrides 表示删除
foreach
动态 SQL 的另外一个常用的操作需求是对一个集合进行遍历,通常是在构建 IN 条件语句的时候。比如:
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
bind
bind 元素可以从 OGNL 表达式中创建一个变量并将其绑定到上下文。比如:
<select id="selectBlogsLike" resultType="Blog">
<bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
SELECT * FROM BLOG
WHERE title LIKE #{pattern}
</select>