码迷,mamicode.com
首页 > 数据库 > 详细

12.动态SQL

时间:2020-05-26 12:21:44      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:一个   声明   sele   字符串   prefix   other   lis   blog   post   

12.动态SQL
if

常用:根据条件包含where子句的一部分

<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>
choose (when , otherwise)

常用:不想使用所有的条件,只从多个条件中选择一个使用,类似于java的switch语句

<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>
trim (where , set)

常用:通过trim元素来定制where元素和set元素的功能

<trim prefix="SET" suffixOverrides=",">
  ...
</trim>

where:

  • where元素只会在子元素返回任何内容的情况下才插入“WHERE”子句

  • 若子句的开头为“AND”或 “OR”,where 元素会将它们去除

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

set:

  • set元素可以用于动态包含需要更新的列,忽略其它不更新的列
  • set元素会动态地在行首插入SET关键字,并会删掉额外的逗号
<update id="updateAuthorIfNecessary">
  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

常用:对集合进行遍历,尤其是在构建 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>

功能:

  1. 允许指定一个集合,声明可以在元素体内使用的集合项item和索引index变量
  2. 允许指定开头与结尾的字符串以及集合项迭代之间的分隔符

使用:可以将任何可迭代对象(List、Set等)、Map对象或者数组对象作为集合参数传递给foreach

  1. 当使用可迭代对象或者数组时,index是当前迭代的序号,item的值是本次迭代获取到的元素
  2. 当使用Map对象(或者Map.Entry对象的集合)时,index是键,item是值

12.动态SQL

标签:一个   声明   sele   字符串   prefix   other   lis   blog   post   

原文地址:https://www.cnblogs.com/thetree/p/12_mybatis.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!