mybatis in查詢條件過長的解決方案

mybatis in查詢條件過長的解決

方法1:分次查詢,將參數且分割成多個短的查詢後合並

代碼:

      int splitNum =(int) Math.ceil( (float) ids.length/999); //切片數量
      List<String> itemIdList = new ArrayList<>(Arrays.asList(ids));
      List<List<String>> splitList = averageAssign(itemIdList, splitNum);
      for (List<String> 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>

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: