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 的數據,參數是一個集合
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的對象,作為入參時
List對象默認用"list"代替作為鍵
數組對象有"array"代替作為鍵,
Map對象沒有默認的鍵。
入參時可以使用@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>
如果是數組類型
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
:集合中元素迭代時的別名,該參數為必選。
index
:在list和數組中,index是元素的序號,在map中,index是元素的key,該參數可選
open
:foreach代碼的開始符號,一般是(和close=")"合用。常用在in(),values()時。該參數可選
separator
:元素之間的分隔符,例如在in()的時候,separator=","會自動在元素中間用“,“隔開,避免手動輸入逗號導致sql錯誤,如in(1,2,)這樣。該參數可選。
close
:foreach代碼的關閉符號,一般是)和open="("合用。常用在in(),values()時。該參數可選。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
IDEA報錯:Unable to save settings Failed to save settings
這篇文章主要介紹了IDEA報錯:Unable to save settings Failed to save settings的相關知識,本文給大家分享問題原因及解決方案,需要的朋友可以參考下2020-09-09Mybatis的collection三層嵌套查詢方式(驗證通過)
這篇文章主要介紹了Mybatis的collection三層嵌套查詢方式(驗證通過),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03Mybatis Generator Plugin悲觀鎖實現示例
本文將從悲觀鎖為例,讓你快速了解如何實現Mybatis Generator Plugin。文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09mybatis配置mapper-locations位置的三種方式小結
這篇文章主要給大家介紹了關于mybatis配置mapper-locations位置的三種方式,Mybatis-Plus的初衷是為了簡化開發(fā),而不建議開發(fā)者自己寫SQL語句的,但是有時客戶需求比較復雜,需要的朋友可以參考下2023-08-08