mybatis錯(cuò)誤之in查詢?<foreach>循環(huán)問題
in查詢 <foreach>循環(huán)問題
當(dāng)我在做in查詢的時(shí)候,發(fā)現(xiàn)在網(wǎng)上有很多種寫法:
接口
public List<CaseReview > findList(CaseReview caseReview);
類
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查詢方法,其實(shí)都在做foreach循環(huán)遍歷
2.findByCaseNos(Long[] caseNos)
如果參數(shù)的類型是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)查詢的參數(shù)有多個(gè)時(shí):
這種情況需要特別注意,在傳參數(shù)時(shí),一定要改用Map方式, 這樣在collection屬性可以指定名稱
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查詢和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è)名字,用于表示在迭代過程中,每次迭代到的位置;open:表示該語(yǔ)句以什么開始;separator:表示在每次進(jìn)行迭代之間以什么符號(hào)作為分隔 符;close:表示以什么結(jié)束;collection:在使用foreach的時(shí)候最關(guān)鍵的也是最容易出錯(cuò)的就是collection屬性,該屬性是必須指定的,但是在不同情況 下,該屬性的值是不一樣的,主要有一下3種情況:
1. 如果傳入的是單參數(shù)且參數(shù)類型是一個(gè)List的時(shí)候,collection屬性值為list
2. 如果傳入的是單參數(shù)且參數(shù)類型是一個(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的類型
? ? ? ? ? ? ?<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的類型
? ? ? ? ? ? ?<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的類型
? ? ? ? ?<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)注過
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
<!-- 查詢申請(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è)查詢時(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è)參考,也希望大家多多支持腳本之家。
- MyBatis中的循環(huán)插入insert foreach問題
- mybatis foreach 循環(huán) list(map)實(shí)例
- MyBatis如何進(jìn)行雙重foreach循環(huán)
- mybatis多個(gè)區(qū)間處理方式(雙foreach循環(huán))
- MyBatis實(shí)現(xiàn)批量插入數(shù)據(jù),多重forEach循環(huán)
- MyBatis中使用foreach循環(huán)的坑及解決
- mybatis insert foreach循環(huán)插入方式
- MyBatis之foreach標(biāo)簽的用法及多種循環(huán)問題
相關(guān)文章
如何解決java.lang.ClassNotFoundException: com.mysql.jdbc.Dr
這篇文章主要介紹了如何解決java.lang.ClassNotFoundException: com.mysql.jdbc.Driver問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
Spring Data Jpa多表查詢返回自定義實(shí)體方式
這篇文章主要介紹了Spring Data Jpa多表查詢返回自定義實(shí)體方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02
Spring報(bào)錯(cuò):Error creating bean with name的問
這篇文章主要介紹了Spring報(bào)錯(cuò):Error creating bean with name的問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
maven中心倉(cāng)庫(kù)OSSRH使用簡(jiǎn)介(推薦)
這篇文章主要介紹了maven中心倉(cāng)庫(kù)OSSRH使用簡(jiǎn)介,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04
Java的JSON轉(zhuǎn)換類庫(kù)GSON的基礎(chǔ)使用教程
GSON是谷歌開源的一款Java對(duì)象與JSON對(duì)象互相轉(zhuǎn)換的類庫(kù),Java的JSON轉(zhuǎn)換類庫(kù)GSON的基礎(chǔ)使用教程,需要的朋友可以參考下2016-06-06
Shiro中session超時(shí)頁(yè)面跳轉(zhuǎn)的處理方式
這篇文章主要介紹了Shiro中session超時(shí)頁(yè)面跳轉(zhuǎn)的處理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06
springboot @ConfigurationProperties和@PropertySource的區(qū)別
這篇文章主要介紹了springboot @ConfigurationProperties和@PropertySource的區(qū)別,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06

