MyBatis 的一个强大的特性之一通常是它的动态 SQL 能力。 如果你有使用 JDBC 或其他 相似框架的经验,你就明白条件地串联 SQL 字符串在一起是多么的痛苦,确保不能忘了空 格或在列表的最后省略逗号。动态 SQL 可以彻底处理这种痛苦。
通常使用动态 SQL 不可能是独立的一部分,MyBatis 当然使用一种强大的动态 SQL 语 言来改进这种情形,这种语言可以被用在任意映射的 SQL 语句中。
动态 SQL 元素和使用 JSTL 或其他相似的基于 XML 的文本处理器相似。在 MyBatis 之 前的版本中,有很多的元素需要来了解。MyBatis 3 大大提升了它们,现在用不到原先一半 的元素就能工作了。MyBatis 采用功能强大的基于 OGNL 的表达式来消除其他元素。
if 语句
<select id="findActiveBlogWithTitleLike" parameterType="Blog" resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<if test="title != null"> AND title like #{title} </if>
</select>
分析:如果客户端传递title值,则查询title相关的内容,否则查询所有。
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 author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
分析: 这和jstl中的一样,cohose中包含和,显然when里面有个test属性进行条件判断,否则条件就执行,所有when不满足才会执行otherwise,相当于if(){}else if(){}else{}.
trim 语句
<trim prefix="A" prefixOverrides="B " suffixOverrides="C"> ... </trim>
分析:trim语句中比较重要的三个属性,prefix表示如果trim内部有条件满足,则会在语句后面添加一个A,如下面的where和update,prefixOverrides是去掉prefix后面第一个字段 B,如下面where中的and 和or,suffixOverrides是去掉trim语句内的最后一个字符C,如下面set的“,”
where语句
<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">
OR author_name like #{author.name}
</if>
</where>
</select>
分析: 使用where语句时,若where语句里面条件都不满足,则不会添加where,查询所有记录,若有一条记录满足,而前面是AND或者OR,则会自动去掉。可用trim语句代替:<trim prefix=“WHERE” prefixOverrides="AND |OR "> … </trim>
set 语句
<update id="updateAuthorIfNecessary" parameterType="domain.blog.Author">
update Author
<set>
<if test="username != null">
username=#{username},
</if>
<if test="password != null">
password=#{password},
</if>
<if test="email != null">
email=#{email},
</if>
<if test="bio != null">
bio=#{bio}
</if>
</set>
where id=#{id}
</update>
分析:与where语句类似,set内部若无条件满足,则不更新,否则会更新满足条件的记录,并把最后一条的逗号给去掉。
可用trim语句: …替代
foreach语句(一般使用在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 元素是非常强大的,它允许你指定一个集合,声明集合项和索引变量,它们可 以用在元素体内。它也允许你指定开放和关闭的字符串,在迭代之间放置分隔符。这个元素 是很智能的,它不会偶然地附加多余的分隔符。
注意:你可以传递一个 List 实例或者数组作为参数对象传给 MyBatis。当你这么做的时 候,MyBatis 会自动将它包装在一个 Map 中,用名称在作为键。List 实例将会以“list” 作为键,而数组实例将会以“array”作为键。