mybatis in查询条件过长的解决方法

54 篇文章 0 订阅
23 篇文章 0 订阅

方法1:分次查询,将参数且分割成多个短的查询后合并
代码:

int splitNum =(int) Math.ceil( (float) ids.length/999); //切片数量
List itemIdList = new ArrayList<>(Arrays.asList(ids));
List<List> splitList = averageAssign(itemIdList, splitNum);
for (List list : splitList) {
param.put(“itemIds”,list);
List<Map<Object, Object>> itemStatisticsList = iProcessExtMapper.getItemStatisticsList(param);
result.addAll(itemStatisticsList);
}

将list分成N等分方法方法:

public static <T> List<List<T>> averageAssign(List<T> source,int n){
List<List<T>> result=new ArrayList<List<T>>();
int remaider=source.size()%n;  //(先计算出余数)
int number=source.size()/n;  //然后是商
int offset=0;//偏移量
for(int i=0;i<n;i++){
 List<T> value=null;
 if(remaider>0){
  value=source.subList(i*number+offset, (i+1)*number+offset+1);
  remaider--;
  offset++;
 }else{
  value=source.subList(i*number+offset, (i+1)*number+offset);
 }
 result.add(value);
}
return result;
}

方法2:xml文件中编写sql

i.id in     
<foreach collection="itemIds" index="index" item="item" open="(" close=")">
<if test="index != 0">
 <choose>
 <when test="index % 1000 == 999"> ) OR ID IN( </when>
               <otherwise>,</otherwise>
 </choose>
</if>
 #{item}
</foreach> 

sql逻辑:

ID IN(ids[0],ids[1]+...+ids[998])OR ID IN (ids[999],ids[1000],...ids[max])

mybatis大于1000的in查询的解决
之前公司一位同事写的方法:

<select id="getByDirIds" parameterType="string" resultMap="dirDocLinkMap">
      SELECT
      <include refid="columns"/>
      FROM KM_DIR_DOC_LINK T
      WHERE T.DIR_ID IN
      <foreach collection="array" index="index" open="(" close=")" item="item" separator=",">
          <if test="(index % 1000) == 999">NULL) OR T.DIR_ID IN (</if>#{item}
      </foreach>
  </select>

但是随着数据量增加,发现大于2000这种方法会报错;论证如下
在这里插入图片描述
解决办法

<foreach collection="array" item="item" index="index" open="(" close=")" separator=",">
              <if test="(index % 999) == 998"> NULL ) OR DOC.ID IN (</if>#{item}
          </foreach>
  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值