• mybatisの动态SQL


    1. 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>
    2. choose when otherwise 不想应用到所有的条件语句,而只想从中择其一项
      <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. where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入“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>
    4. 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>
    5. 动态 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>

      注意:当使用可迭代对象或者数组时,index 是当前迭代的次数,item 的值是本次迭代获取的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

    6. 官网地址 http://www.mybatis.org/mybatis-3/zh/dynamic-sql.html
  • 相关阅读:
    BZOJ 2789: [Poi2012]Letters 树状数组 + 逆序对
    luogu 5468 [NOI2019]回家路线 最短路/暴力
    BZOJ 2427: [HAOI2010]软件安装 tarjan + 树形背包
    练手爬虫用urllib模块获取
    django安装以及配置
    web框架
    模拟百度进行图片搜索,有问题可以留言
    深入requests库params|data|json参数
    深入理解http1.x、http 2和https
    nodejs 实现 磁力链接资源搜索 BT磁力链接爬虫
  • 原文地址:https://www.cnblogs.com/yangjiming/p/9579406.html
Copyright © 2020-2023  润新知