Mybatis用注解寫in查詢的實現(xiàn)
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ù)可選。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
springmvc級聯(lián)屬性處理無法轉換異常問題解決
這篇文章主要介紹了springmvc級聯(lián)屬性處理無法轉換異常問題解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-12-12
Java實現(xiàn)學生管理系統(tǒng)(控制臺版本)
這篇文章主要為大家詳細介紹了如何利用Java語言實現(xiàn)控制臺版本的學生管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-06-06
SpringBoot之spring.factories的使用方式
這篇文章主要介紹了SpringBoot之spring.factories的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01
Spring+Hibernate+Struts(SSH)框架整合實戰(zhàn)
SSH是 struts+spring+hibernate的一個集成框架,是目前比較流行的一種Web應用程序開源框架。本篇文章主要介紹了Spring+Hibernate+Struts(SSH)框架整合實戰(zhàn),非常具有實用價值,需要的朋友可以參考下2018-04-04

