zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    jQuery的选择器中的通配符[id^='code']
    浏览器调试js
    google浏览器调试js
    【暑假】[实用数据结构]UVAlive 3026 Period
    【暑假】[实用数据结构]UVAlive 3942 Remember the Word
    【暑假】[实用数据结构] AC自动机
    【暑假】[实用数据结构]KMP
    【暑假】[实用数据结构]前缀树 Trie
    【暑假】[实用数据结构]UVa11235 Frequent values
    【暑假】[实用数据结构]UVAlive 4329 Ping pong
  • 原文地址:https://www.cnblogs.com/yangjiming/p/9579406.html
Copyright © 2011-2022 走看看