mybatis动态sql

时间:2023-03-08 20:24:24

MyBatis 采用功能强大的基于 OGNL 的表达式来消除其他元素。

 if
 choose(when,otherwise)
 trim(where,set)
 foreach
例子(2):
<select id=”findActiveBlogLike”  parameterType=”Blog” resultType=”Blog”>
SELECT * FROM BLOG WHERE state = „ACTIVE‟
<if test=”title != null”>
AND title like #{title}
</if>
<if test=”author != null and author.name != null”>
AND title like #{author.name}
</if>
</select>
choose, when, otherwise
例子(2):
<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”> //当有一个<when>的条件满足时,其他的<when>就不执行(switch
AND title like #{author.name}
</when>
<otherwise> //<!--只有在<when>的条件全部不满足的时候,otherwise才会起作用 -->
AND featured = 1
</otherwise>
</choose>
</select>
例子(2-1):
<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 不插入。
你可以使用 trim 元素来自定义。比如,和 where
元素相等的 trim 元素是:
<trim prefix="WHERE" prefixOverrides="AND |OR ">

</trim> // overrides 属性采用管道文本分隔符来覆盖,这里的空白也是重要的。它的结果就是移除在 overrides
// 属性中指定的内容插入在 with 属性中的内容。
和动态更新语句相似的解决方案是 set。 set 元素可以被用于动态包含更新的列,而不包
含不需更新的(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>

这里, set 元素会动态前置 SET 关键字,而且也会消除任意无关的逗号,那也许在应用
条件之后来跟踪定义的值。

如果你对和这相等的 trim 元素好奇,它看起来就是这样的:
<trim prefix="SET" suffixOverrides=",">

</trim>