mybatis錯(cuò)誤之in查詢(xún)?<foreach>循環(huán)問(wèn)題
in查詢(xún) <foreach>循環(huán)問(wèn)題
當(dāng)我在做in查詢(xún)的時(shí)候,發(fā)現(xiàn)在網(wǎng)上有很多種寫(xiě)法:
接口
public List<CaseReview > findList(CaseReview caseReview);
類(lèi)
public class CaseReview{
private String caseNo;
private List<String> caseNos;//caseNo
//===gettter,setter省略===
}1.我就隨便用了一種傳list,再foreach循環(huán)
具體如下:
t.case_no in?
<foreach item="item" index="index" collection="caseNos" open="(" separator="," close=")"> ?
#{item} ?
</foreach>?然而報(bào):
org.apache.ibatis.reflection.ReflectionException: There is no getter for property named '__frch_item_0' in 'class
于是解決辦法就出來(lái)了:
就是將 #{item} 改為 ‘${item}’就搞定了
<foreach item="item" index="index" collection="caseNos" open="(" separator="," close=")"> ?
? ?'${item}' ?
</foreach>如果你非要用#也不是不可以
<foreach item="item" index="index" collection="caseNos" open="(" separator="," close=")"> ?
? ? ? ? ? ? ?#{caseNos[${index}]} ?
</foreach>還有兩種in查詢(xún)方法,其實(shí)都在做foreach循環(huán)遍歷
2.findByCaseNos(Long[] caseNos)
如果參數(shù)的類(lèi)型是Array,則在使用時(shí),collection屬性要必須指定為 array
?caseNos in ?
? ? <foreach item="item" index="index" collection="array" open="(" separator="," close=")"> ?
? ? ?#{caseNos}
? ? </foreach> ?3.findByCaseNos(String name, Long[] caseNos)
當(dāng)查詢(xún)的參數(shù)有多個(gè)時(shí):
這種情況需要特別注意,在傳參數(shù)時(shí),一定要改用Map方式, 這樣在collection屬性可以指定名稱(chēng)
Map<String, Object> params = new HashMap<String, Object>();
?params.put("name", name);
?params.put("ids", caseNos);
?mapper.findByIdsMap(params);?caseNos in ?
? ? ?<foreach item="item" index="index" collection="caseNos" open="(" separator="," close=")"> ?
? ? ? #{item} ?
? ? ?</foreach>
in查詢(xún)和foreach標(biāo)簽使用
Mybatis中的foreach的主要用在構(gòu)建in條件中,它可以在SQL語(yǔ)句中進(jìn)行迭代一個(gè)集合。
foreach元素的屬性主要有 item,index,collection,open,separator,close:
item:表示集合中每一個(gè)元素進(jìn)行迭代時(shí)的別;index:指定一個(gè)名字,用于表示在迭代過(guò)程中,每次迭代到的位置;open:表示該語(yǔ)句以什么開(kāi)始;separator:表示在每次進(jìn)行迭代之間以什么符號(hào)作為分隔 符;close:表示以什么結(jié)束;collection:在使用foreach的時(shí)候最關(guān)鍵的也是最容易出錯(cuò)的就是collection屬性,該屬性是必須指定的,但是在不同情況 下,該屬性的值是不一樣的,主要有一下3種情況:
1. 如果傳入的是單參數(shù)且參數(shù)類(lèi)型是一個(gè)List的時(shí)候,collection屬性值為list
2. 如果傳入的是單參數(shù)且參數(shù)類(lèi)型是一個(gè)array數(shù)組的時(shí)候,collection的屬性值為array
3. 如果傳入的參數(shù)是多個(gè)的時(shí)候,我們就需要把它們封裝成一個(gè)Map了,當(dāng)然單參數(shù)也可以封裝成map,實(shí)際上如果你在傳入?yún)?shù)的時(shí)候,在breast里面也是會(huì)把它封裝成一個(gè)Map的,map的key就是參數(shù)名,所以這個(gè)時(shí)候collection屬性值就是傳入的List或array對(duì)象在自己封裝的map里面的key
下面分別來(lái)看看上述三種情況的示例代碼:
1.單參數(shù)List的類(lèi)型
? ? ? ? ? ? ?<select id="dynamicForeachTest" resultType="Blog">
? ? ? ? ? ? ? ? ? ? select * from t_blog where id in
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #{item}
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? </foreach>
? ? ? ? ? ?</select>上述collection的值為list,對(duì)應(yīng)的Mapper是這樣的:
public List<Blog> dynamicForeachTest(List<Integer> ids);
測(cè)試代碼:
? ? ? ? ? ? ? @Test
? ? ? ? ? ? ? public void dynamicForeachTest() {
? ? ? ? ? ? ? ? ? ? ? ?SqlSession session = Util.getSqlSessionFactory().openSession();
? ? ? ? ? ? ? ? ? ? ? ?BlogMapper blogMapper = session.getMapper(BlogMapper.class);
? ? ? ? ? ? ? ? ? ? ? ?List<Integer> ids = new ArrayList<Integer>();
? ? ? ? ? ? ? ? ? ? ? ?ids.add(1);
? ? ? ? ? ? ? ? ? ? ? ?ids.add(3);
? ? ? ? ? ? ? ? ? ? ? ?ids.add(6);
? ? ? ? ? ? ? ? ? ? ? ?List<Blog> blogs = blogMapper.dynamicForeachTest(ids);
? ? ? ? ? ? ? ? ? ? ? ?for (Blog blog : blogs){
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? System.out.println(blog);
? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ? ? session.close();
? ? ? ? ? ? ?}2.單參數(shù)Array的類(lèi)型
? ? ? ? ? ? ?<select id="dynamicForeach2Test" resultType="Blog">
? ? ? ? ? ? ? ? ? ? ?select * from t_blog where id in
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?<foreach collection="array" index="index" item="item" open="(" separator="," close=")">
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #{item}
? ? ? ? ? ? ? ? ? ? ? ? ? ? </foreach>
? ? ? ? ? ? </select>上述collection為array,對(duì)應(yīng)的Mapper代碼:
public List<Blog> dynamicForeach2Test(int[] ids);
對(duì)應(yīng)的測(cè)試代碼:
@Test
? ? ? ? ?public void dynamicForeach2Test() {
? ? ? ? ? ? ? ? ? SqlSession session = Util.getSqlSessionFactory().openSession();
? ? ? ? ? ? ? ? ? BlogMapper blogMapper = session.getMapper(BlogMapper.class);
? ? ? ? ? ? ? ? ? int[] ids = new int[] {1,3,6,9};
? ? ? ? ? ? ? ? ? List<Blog> blogs = blogMapper.dynamicForeach2Test(ids);
? ? ? ? ? ? ? ? ? for (Blog blog : blogs){
? ? ? ? ? ? ? ? ? ? ? ? ? System.out.println(blog);
? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ?session.close();
? ? ? ? ? ?}3.多參數(shù)封裝成Map的類(lèi)型
? ? ? ? ?<select id="dynamicForeach3Test" resultType="Blog">
? ? ? ? ? ? ? ? ? ? select * from t_blog where title like "%"#{title}"%" and id in
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?<foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?#{item}
? ? ? ? ? ? ? ? ? ? ? ? ? ? </foreach>
? ? ? ? </select>上述collection的值為ids,是傳入的參數(shù)Map的key,對(duì)應(yīng)的Mapper代碼:
public List<Blog> dynamicForeach3Test(Map<String, Object> params);
對(duì)應(yīng)測(cè)試代碼:
@Test
? ? ? ? public void dynamicForeach3Test() {
? ? ? ? ? ? ? ? ?SqlSession session = Util.getSqlSessionFactory().openSession();
? ? ? ? ? ? ? ? ?BlogMapper blogMapper = session.getMapper(BlogMapper.class);
? ? ? ? ? ? ? ? ?final List<Integer> ids = new ArrayList<Integer>();
? ? ? ? ? ? ? ? ?ids.add(1);
? ? ? ? ? ? ? ? ?ids.add(2);
? ? ? ? ? ? ? ? ?ids.add(3);
? ? ? ? ? ? ? ? ?ids.add(6);
? ? ? ? ? ? ? ? ?Map<String, Object> params = new HashMap<String, Object>();
? ? ? ? ? ? ? ? ?params.put("ids", ids);
? ? ? ? ? ? ? ? ?params.put("title", "中國(guó)");
? ? ? ? ? ? ? ? ?List<Blog> blogs = blogMapper.dynamicForeach3Test(params);
? ? ? ? ? ? ? ? ?for (Blog blog : blogs)
? ? ? ? ? ? ? ? ? ? ? ?System.out.println(blog);
? ? ? ? ? ? ? ? ?session.close();
? ? ? ? }4.嵌套foreach的使用
map 數(shù)據(jù)如下 Map<String,List<Long>>
測(cè)試代碼如下:
? ? ? ?public void getByMap(){
? ? ? ? Map<String,List<Long>> params=new HashMap<String, List<Long>>();
? ? ? ? List<Long> orgList=new ArrayList<Long>();
? ? ? ? orgList.add(10000003840076L);
? ? ? ? orgList.add(10000003840080L);
? ? ? ??
? ? ? ? List<Long> roleList=new ArrayList<Long>();
? ? ? ? roleList.add(10000000050086L);
? ? ? ? roleList.add(10000012180016L);
? ? ? ??
? ? ? ? params.put("org", orgList);
? ? ? ? params.put("role", roleList);
? ? ? ??
? ? ? ? List<BpmDefUser> list= bpmDefUserDao.getByMap(params);
? ? ? ? System.out.println(list.size());
? ? }dao代碼如下:
public List<BpmDefUser> getByMap(Map<String,List<Long>> map){
? ? ? ? ? ? Map<String,Object> params=new HashMap<String, Object>();
? ? ? ? ? ? params.put("relationMap", map);
? ? ? ? ? ? return this.getBySqlKey("getByMap", params);
? ? }xml代碼如下:
<select id="getByMap" resultMap="BpmDefUser">
? ? ? ??
? ? ? ? ? ? <foreach collection="relationMap" index="key" ?item="ent" separator="union">
? ? ? ? ? ? ? ? SELECT *
? ? ? ? ? ? ? ? FROM BPM_DEF_USER
? ? ? ? ? ? ? ? where ?RIGHT_TYPE=#{key}
? ? ? ? ? ? ? ? and OWNER_ID in?
? ? ? ? ? ? ? ? <foreach collection="ent" ?item="id" separator="," open="(" close=")">
? ? ? ? ? ? ? ? ? ? #{id}
? ? ? ? ? ? ? ? </foreach>
? ? ? ? ? ? </foreach>
? ? ? ??
? ? </select>index 作為map 的key。item為map的值,這里使用了嵌套循環(huán),嵌套循環(huán)使用ent。
《項(xiàng)目實(shí)踐》
@Override
public Container<Map<String,Object>> findAuditListInPage(
Map<String, Object> params) {
//1、參數(shù)組裝
PageModel pageMode = new PageModel();
try {
if(params.get("page")!=null){
pageMode.setPage(Integer.parseInt(params.get("page").toString()));
}
if(params.get("rows")!=null){
pageMode.setRows(Integer.parseInt(params.get("rows").toString()));
}
} catch (Exception e) {
Assert.customException(RestApiError.COMMON_ARGUMENT_NOTVALID);
}
//分頁(yè)條件組裝
pageMode.putParam(params);
if(params.get("startCreateTime") !=null){
Date parse = DateUtil.parse(params.get("startCreateTime").toString(), DateUtil.yyyyMMddHHmmss);
params.put("startCreateTime",parse);
}
if(params.get("endCreateTime") !=null){
Date parse = DateUtil.parse(params.get("endCreateTime").toString(), DateUtil.yyyyMMddHHmmss);
params.put("endCreateTime",parse);
}
if(params.get("type") !=null){ ?//type可以多選
String typeString = params.get("type").toString();
String typeArray [] = typeString.split(",");
params.put("type", typeArray);
}
if(params.get("state") !=null){ ?//state可以多選
String stateString = params.get("state").toString();
if(stateString.equals(DictConstants.APPLICATION_STATE.AUDITING)
? ? ? ? ? ? ? ?||stateString.equals(DictConstants.APPLICATION_STATE.WAITING_AUDIT)){
stateString = "waitingAudit,auditing";
}
String stateArray [] = stateString.split(",");
params.put("state", stateArray);
}
//分頁(yè)數(shù)據(jù)組裝
Container<Map<String,Object>> container = new Container<Map<String,Object>>();
List<Map<String,Object>> auditModelList = cmApplicationRepo.findAuditList(params);
for(Map<String,Object> audit:auditModelList){
//設(shè)置是否關(guān)注過(guò)
Long auditId = Long.parseLong(audit.get("auditId").toString());
Long auditPersonId = Long.parseLong(params.get("auditPersonId").toString());
Map<String, Object> followMap = new HashMap<String,Object>();
followMap.put("sourceType", DictConstants.FOLLOW_SOURCE_TYPE.FOLLOW_APPLICATION);
followMap.put("sourceId", auditId);
followMap.put("userId", auditPersonId);
List<BizFollowModel> followList = bizFollowService.find(followMap);
if(followList!= null && followList.size()>0){
audit.put("isFollow", "true");
}else{
audit.put("isFollow", "false");
}
}
container.setList(auditModelList);
container.setTotalNum(cmApplicationRepo.countAuditListNumber(params));
return container;
}DAO
@Override
public List<Map<String,Object>> findAuditList(Map<String, Object> map) {
return findList("getAuditList", map);
}xml
<!-- 查詢(xún)申請(qǐng)列表-->
<select id="getApplicationList" resultType="java.util.Map" parameterType="map">
select
a.ID AS id,
a.STATE AS stateCode, b.DICT_VALUE AS stateValue,
a.ITEM AS itemCode, c.DICT_VALUE AS itemValue,
a.TYPE AS typeCode, d.DICT_VALUE AS typeValue,
a.APP_PERSON_ID AS appPersonId,
a.CREATE_TIME AS createTime
from cm_application a
LEFT JOIN cm_dict_type b on a.STATE = b.DICT_CODE AND b.TYPE = 'Application_State'
LEFT JOIN cm_dict_type c on a.ITEM = c.DICT_CODE
LEFT JOIN cm_dict_type d on a.TYPE = d.DICT_CODE
where 1=1
<if test="item != null" >
and a.ITEM = #{item,jdbcType=VARCHAR}
</if>
<if test="type != null" >?
and a.TYPE IN?
<foreach item="typeArray" index="index" collection="type" open="(" separator="," close=")">
#{typeArray}
</foreach>
</if>
<if test="appPersonId != null" >
and a.APP_PERSON_ID = #{appPersonId,jdbcType=BIGINT}
</if>
<if test="state != null" >
and a.STATE IN
<foreach item="stateArray" index="index" collection="state" open="(" separator="," close=")">
#{stateArray}
</foreach>
</if>
<!-- 分頁(yè)查詢(xún)時(shí),要選擇createTime在starCreateTime和endCreatetTime之間的記錄 -->
<if test="startCreateTime != null" >
and a.CREATE_TIME >= #{startCreateTime,jdbcType=TIMESTAMP}
</if>
<if test="endCreateTime != null" >
and a.CREATE_TIME <= #{endCreateTime,jdbcType=TIMESTAMP}
</if>
order by a.ID
<include refid="Paging" />
</select>以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
MyBatis?和?jeesite多表查詢(xún)示例詳解
這篇文章主要介紹了MyBatis?和?jeesite多表查詢(xún),本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-04-04
Java使用elasticsearch基礎(chǔ)API使用案例講解
這篇文章主要介紹了Java使用elasticsearch基礎(chǔ)API使用案例講解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08
springboot中swagger快速啟動(dòng)流程
這篇文章主要介紹了springboot中的swagger快速啟動(dòng)流程,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-09-09
Spring AI集成DeepSeek三步搞定Java智能應(yīng)用的詳細(xì)過(guò)程
本文介紹了如何使用SpringAI集成DeepSeek,一個(gè)國(guó)內(nèi)頂尖的多模態(tài)大模型,SpringAI提供了一套統(tǒng)一的接口,簡(jiǎn)化了與不同AI模型的集成,通過(guò)配置文件和簡(jiǎn)單的接口調(diào)用,開(kāi)發(fā)者可以方便地使用DeepSeek進(jìn)行數(shù)學(xué)推理、代碼生成等任務(wù),感興趣的朋友一起看看吧2025-03-03
Java自動(dòng)化讀取Excel文件(XLS/XLSX)的完整指南
這篇文章詳細(xì)介紹了如何使用該庫(kù)讀取XLS和XLSX格式的Excel文件,包括提取單元格數(shù)據(jù)、公式計(jì)算結(jié)果以及圖像等內(nèi)容,希望可以幫助大家快速實(shí)現(xiàn)Excel文檔的自動(dòng)化處理與集成2025-09-09
SpringCloud中使用Sentinel實(shí)現(xiàn)限流的實(shí)戰(zhàn)
限流在很多地方都可以使用的到,本篇博客將介紹如何使用SpringCloud中使用Sentinel實(shí)現(xiàn)限流,從而達(dá)到服務(wù)降級(jí)的目的,感興趣的可以了解一下2022-01-01
SpringBoot自定義Starter實(shí)現(xiàn)流程詳解
SpringBoot中的starter是一種非常重要的機(jī)制,能夠拋棄以前繁雜的配置,將其統(tǒng)一集成進(jìn)starter,應(yīng)用者只需要在maven中引入starter依賴(lài),SpringBoot就能自動(dòng)掃描到要加載的信息并啟動(dòng)相應(yīng)的默認(rèn)配置。starter讓我們擺脫了各種依賴(lài)庫(kù)的處理,需要配置各種信息的困擾2022-09-09

