MyBatis的动态SQL

动态SQL

MaBatis的一个强大的特性之一就是它的动态SQL能力。如果你哟使用JDBC或其他相似框架的经历,那么你就知道串联SQL语句是多么痛苦的事。

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

(1)if

(2)choose(when,otherwise)

(3)trim(where,set)

(4)foreach

 

(1)if

在动态SQL中所做的最通常的事情是包含部分where字句的条件。比如:

<select id="id" parameterType="Blog" resultType="Blog">

  select * from BLOG where state='active' <if test="title != null">and title like #{title}</if>

</select>

这条语句是一条可选择的文本查询功能,如果title为null,返回所有的Blog,如果不为null,则会查询like语句。

假如选择条件是title和author,需要加上另一个条件。

seelct * 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>

(2)choose

有时候我们不想应用所有的条件,只想选择很多情况中的一种。和java 中的swith语句相似,MyBatis提供了choose元素。

当title提供时,仅有title条件,当author提供时,仅有author条件,若二者都没有提供,只返回featured blogs。

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>

(3)where

将active=1时,可以用

<where>

  <if test="state !=null">

    state=#{state}

  </if>

  <if test="title !=null">

    and title lile #{title}

  </if>

  <if test="author !=null and author.name !=null">

    and title like #{author.name}

  </if>

</where>

where 元素知道如果有被包含的标记返回任意内容,就仅仅插入“where”。而且,如果以“and”或"or"开头的内容,会跳过where不插入。

如果where元素没有做到你想要的,可以使用trim元素来自定义,比如:

和where元素是一样的元素trim元素是:

<trim prefix="where" prefixOverrides="and|or">

</trim>

set元素可以 被用于动态包含更新列,而不包含不需要更新的。比如:

<update id="id" parameterType="author">

  update Author

  <set>

    <if test="username !=null">username=#{username},</if>

    <if test="password !=null">password=#{password},</if>

  </set>

  where id=#{id}

这里,set元素会动态前置set关键字,而且也会消除任意无关的逗号。

这相等的trim元素

<trim prefix="set" suffixOverrides=",">

</trim>

这种情况覆盖了一个后缀,同时附加前缀。

(4)foreach

<select id="id" resultType="Post">

  select * from Post P where id in

    <foreach item="item" index="index" collection="list" open="(" separator="," colse=")">

      #{item}

    </foreach>

</select>

</update>

 

posted @ 2017-08-25 16:53  Jston  阅读(165)  评论(0)    收藏  举报