MyBaties动态SQL的常用标签及用法

MyBatis中用于实现动态SQL的元素主要有:

  1. if
  2. choose(when,otherwise)
  3. trim
  4. where
  5. set
  6. foreach

(1).if标签:条件判断

<select id="findActiveBlogLike" 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 author_name like #{author.name}
  </if>
</select>

(2).choose, when, otherwise标签:复杂条件判断

mybatis并没有if…else,在mybatis的sql mapper文件中,条件判断要用choose…when…otherwise。

choose 标签是按顺序判断其内部 when 标签中的 test 条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when 的条件都不满足时,则执行 otherwise 中的sql。类似于Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。

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

(3).trim, where, set标签

<select id="findActiveBlogLike" 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 author_name like #{author.name}
    </if>
  </where>
</select>

where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入 “WHERE” 子句。而且,若语句的开头为 “AND” 或 “OR” ,where 元素也会将它们去除。

(4).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>

oreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及在迭代结果之间放置分隔符。这个元素是很智能的,因此它不会偶然地附加多余的分隔符。

猜你喜欢

转载自blog.csdn.net/qq_45349018/article/details/104852057