mybatis处理集合、数组参数使用in查询

对于mybatis的参数类型是集合数组的时候进行查询。

 

第一种:参数list ,使用mybatis的标签

 1 SELECT  * FROM  TABLE_NAME AS a WHERE
 2 
 3 a.id not in #{extraIds}
 4 <foreach collection="extraIds" item="extraId" index="i" open="(" separator="," close=")">
 5         #{extraId}
 6 
 7 </foreach>
 8 
 9 参数讲解的:
10 
11 collection:需要循环的集合
12 
13 item:每次循环的参数名字
14 
15 index:索引(0开始)
16 
17 separator:分隔符
18 
19 open:整个循环开始的分隔符
20 
21 close:整个循环结束的分隔符
View Code

 

第二种:参数string的数组,即:${}

需要处理参数形成extraIds=('1','2','3')这种类型,需要拼接字符 ''

或直接使用extraIds=("1,2,3")这种类型

注意在mybatis中使用的是${},不能使用#{}否则报错

 1 SELECT  * FROM  TABLE_NAME AS a WHERE
 2 
 3 a.id not in ${extraIds}
 4 
 5 一小段示类代码:
 6 
 7 String extraIds = "1,2,3,4,5";
 8 
 9  String[] extraIdArray = extraIds.split(",");
10             extIds = "";
11             for (String extraId : extraIdArray) {
12                 if (extraId != null && !"".equals(extraId)) {
13                     extraIds += ",'" + extraId + "'";
14                 }
15 
16             }
17 
18  extraIds   =    "(" + extraIds.substring(1) + ")"
19 
20 拼接后:('1','2','3','4','5')
View Code

 

第三种:使用QueryWrapper 直接用list

 

1 List<Integer> activityHelpSponsorIds = Arrays.asList(1,2,3);
2 QueryWrapper<HelpLog> queryWrapper = new QueryWrapper<>();
3 queryWrapper.lambda().in(HelpLog::getActivityHelpSponsorId, activityHelpSponsorIds);
4 List<HelpLog> helperlogList = helpLogService.list(queryWrapper);
View Code

 

posted on 2020-11-11 11:02  腾逸  阅读(2209)  评论(0编辑  收藏  举报