MyBatis高級篇 - 動(dòng)態(tài)SQL

mybatis

描述

MyBatis提供了一套動(dòng)態(tài)SQL標(biāo)簽,協(xié)助我們完成 SQL 語句的拼接工作。我們在日常工作中經(jīng)常需要對 SQL 進(jìn)行拼接:入?yún)⒀h(huán)遍歷, where 條件拼接時(shí)的分隔符處理等等。
本文介紹以下幾個(gè)較常用的動(dòng)態(tài)SQL標(biāo)簽:

  • if
  • where
  • foreach
  • sql

if

我們經(jīng)常會遇到 where 條件中需要根據(jù)是否傳入?yún)?shù)來確定是否添加條件。

    <select id="findUser" parameterType="userInfo" resultType="userInfo">
        SELECT * FROM user_info WHERE 1=1
                <if test="name != null and name.length() > 0 " >
                    AND name=#{name}
                </if>
    </select>
  • test 屬性用于條件判斷
  • where 條件中的 1=1 就是為了避免 <if>如果判斷為空時(shí),不會只返回 'select * from user_info where' 導(dǎo)致 SQL 無法運(yùn)行。不過這樣的寫法會導(dǎo)致索引無法使用。

where

為了解決上面所遇到的問題,MyBatis 為我們提供了 <where> 標(biāo)簽。

<select id="findUser" parameterType="userInfo" resultType="userInfo">
  SELECT * FROM user_info
  <where>
    <if test="name != null and name.length() > 0 " >
     AND name=#{name}
     </if>
  </where>
</select>
  • 當(dāng) <where> 標(biāo)簽會在子元素有返回內(nèi)容時(shí),才會插入 "WHERE" 子句
  • <where> 標(biāo)簽會為我們?nèi)コ谝粋€(gè) "AND" 或 "OR"

foreach

<foreach> 用于遍歷輸入?yún)?shù)中集合對象。

<select id="query_order_by_ids" >
  SELECT * FROM orders
  <where>
     <if test="ids != null && ids.size > 0 " >
        <foreach collection="ids" item="id" index="index" open=" AND id IN ("  close=")" separator="," >
          #{id}
        </foreach>
     </if>
  </where>
</select>
  • collection 代表待遍歷的集合,如果輸入?yún)長ist 或 Array,則 collection屬性值只能固定寫 list 或 array
  • item 代表集合中的某一個(gè)元素
  • index 代表遍歷的序號,如果遍歷對象為 Map(或者M(jìn)ap.Entry對象),則 index 代表 key
  • open 代表拼接在遍歷內(nèi)容前的字符串
  • close 代表拼接在遍歷內(nèi)容后的字符串

sql

我們的 Mapper 文件,在 select 或者是 where 經(jīng)常會出現(xiàn)重復(fù)內(nèi)容,我們可以把重復(fù)的內(nèi)容抽取為一個(gè) <sql> 片段,需要使用的地方,使用 <include> 標(biāo)簽就可以引入進(jìn)來。

<sql id="query_order_where" >
   <if test="ids != null && ids.size > 0 " >
        <foreach collection="ids" item="id" index="index" open=" AND id IN ("  close=")" separator="," >
          #{id}
        </foreach>
     </if>
</sql>
<select id="query_order_by_ids" >
  SELECT * FROM orders
  <where>
    <include refid="query_order_where" ></include>
  </where>
</select>
碼字不易,感謝點(diǎn)贊打賞
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容