溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Mybatis怎么用注解寫in查詢

發(fā)布時間:2021-07-13 12:24:00 來源:億速云 閱讀:1348 作者:小新 欄目:開發(fā)技術

這篇文章主要為大家展示了“Mybatis怎么用注解寫in查詢”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“Mybatis怎么用注解寫in查詢”這篇文章吧。

Mybatis注解寫in查詢

@Select("<script>"
        + "SELECT * FROM table WHERE OrderNo IN "
        + "<foreach item='item' index='index' collection='list'      open='(' separator=',' close=')'>"
        + "#{item}"
        + "</foreach>"
        + "</script>")
List<Map<String,Object>> selectdemo(@Param("list") List<String> list);

這里foreach里面的collection值寫@Param值。

Mybatis中IN語句查詢、Mybatis中的foreach用法

1 需求

查詢 用戶 ID 為 101、102、103 的數(shù)據(jù),參數(shù)是一個集合

2 在 SQL 語句中

select * from t_user where user_id in ( '101' , '102' ,'103')

3 在 Mybatis 中

你只需要

<select id="selectUserByIdList" resultMap="usesInfo">
 SELECT
 *
 from t_user
 WHERE id IN
 <foreach collection="idList" item="id" index="index" open="(" close=")" separator=",">
   #{id}
 </foreach>
</select>

對應的 Mapper中的接口如下

List<UserInfo> selectUserByIdList(@Param("idList")List idList)

4 聊一下

foreach元素的屬性主要有collection,item,index,open,separator,close。

4.1 collection

用來標記將要做foreach的對象,作為入?yún)r

List對象默認用"list"代替作為鍵

數(shù)組對象有"array"代替作為鍵,

Map對象沒有默認的鍵。

入?yún)r可以使用@Param(“keyName”)來設置鍵,設置keyName后,默認的list、array將會失效。

如下的查詢也可以寫成如下

List<UserInfo> selectUserByIdList(List idList)
<select id="selectUserByIdList" resultMap="usesInfo">
 SELECT
 *
 from t_user
 WHERE id IN
 <foreach collection="list" item="id" index="index" open="(" close=")" separator=",">
   #{id}
 </foreach>
</select>

如果是數(shù)組類型

List<UserInfo> selectUserByIdList(Long[] idList)
<select id="selectUserByIdList" resultMap="usesInfo">
 SELECT
 *
 from t_user
 WHERE id IN
 <foreach collection="array" item="id" index="index" open="(" close=")" separator=",">
   #{id}
 </foreach>
</select>

4.2

item:集合中元素迭代時的別名,該參數(shù)為必選。

index:在list和數(shù)組中,index是元素的序號,在map中,index是元素的key,該參數(shù)可選

open:foreach代碼的開始符號,一般是(和close=")"合用。常用在in(),values()時。該參數(shù)可選

separator:元素之間的分隔符,例如在in()的時候,separator=","會自動在元素中間用“,“隔開,避免手動輸入逗號導致sql錯誤,如in(1,2,)這樣。該參數(shù)可選。

close:foreach代碼的關閉符號,一般是)和open="("合用。常用在in(),values()時。該參數(shù)可選。

以上是“Mybatis怎么用注解寫in查詢”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI