MyBatis动态sql

随声附和 提交于 2020-03-08 18:53:41

利用动态 SQL可以很方便地根据不同条件拼接 SQL 语句

 

if

常用于根据条件拼接where 子句。

示例:

<select id="find" resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <if test="title != null">
    AND title like #{title}
  </if>
</select>

说明:如果没有传入“title”,只返回处于“ACTIVE”状态的BLOG;反之,返回处于“ACTIVE”状态且对“title” 进行一列模糊查找的BLOG 结果。

示例:

<select id="find" 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>

where

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

示例:

<select id="find" 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>

 

 

 

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

  SELECT * FROM BLOG WHERE 1=1

  <if test="state != null">

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

</select>

 

set

set 元素可以用于动态包含需要更新的列,而删掉无关的逗号

示例:

<update id="update">
  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>

foreach

foreach元素用于对一个集合进行遍历,构建 IN 条件语句时常用该元素;foreach 元素允许指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量,也允许指定开头与结尾的字符串以及在迭代结果之间放置分隔符。

示例:

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

注意:可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象传递给 foreach 作为集合参数;当使用可迭代对象或者数组时,index 是当前迭代的次数,item 的值是本次迭代获取的元素;当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

 

官网:https://mybatis.org/mybatis-3/zh/dynamic-sql.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!