<select id=”findActiveBlogWithTitleLike”
parameterType=”Blog” resultType=”Blog”>
SELECT * FROM BLOG
WHERE state = ?ACTIVE?
<if test=”title != null”>
AND title like #{title}
</if>
</select>
choose, when, otherwise
和Java中的switch语句相似,MyBatis提供choose元素。
<select id=”findActiveBlogLike”
parameterType=”Blog” 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 title like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
trim, where, set 上面的例子中如果把“state = ?ACTIVE?”也设置为动态的话就有可能出现问题。所以,<select id=”findActiveBlogLike”
parameterType=”Blog” 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 title like #{author.name}
</if>
</where>
</select>where元素知道如果由被包含的标记返回任意内容,就仅仅插入“WHERE”。而且,如果以“AND”或“OR”开头的内容,那么就会跳过WHERE不插入。
另外一个动态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>foreach元素是非常强大的,它允许你指定一个集合,声明集合项和索引变量,它们可以用在元素体内。它也允许你指定开放和关闭的字符串,在迭代之间放置分隔符。这个元素是很智能的,它不会偶然地附加多余的分隔符。