近期在代码开发中,发现某些业务场景因为多个服务的调用查询,避免不了使用in,当in的数量小于1000的时候,可以正常使用,但是当in的数量大于1000的时候就会出现报错,针对此类问题主要有两个场景:1.使用Mybatis在XML中写SQL;2.使用MybatisPlus
1. 使用Mybatis在xml中写SQL
思路:将大于1000的条件切割成多段。
代码部分:
/**
* 切割List的工具类
*/
public class ListSplitUtils {
/**
* list 分割
* @param list 待切割list
* @param length 切割长度
*/
public static <T> List<List<T>> spiltList (List<T> list, int length){
int size = list.size();
// 切割数量
int count = (size + length - 1) / length;
List<List<T>> resultList = new ArrayList<>(count);
for(int i = 0; i < count; i++){
// 开始位置
int fromIndex = i * length;
// 结束位置
int toIndex = Math.min((i + 1) * length, size);
resultList.add(list.subList(fromIndex, toIndex));
}
return resultList;
}
}
xml 部分:
<if test="params.idList != null and params.idList.size() > 0">
AND (t.id IN
<foreach collection="params.idList" index="index" open="(" close=")" item="item" >
<if test="index !=0">
<choose>
<when test="index % 1000 == 999">) OR t.id IN (</when>
<otherwise>,</otherwise>
</choose>
</if>
#{item}
</foreach>
)
</if>
2. 使用MybatisPlus
思路:同样是将大于1000的条件切割成多段。
工具类
/**
* 切割List的工具类
*/
public class MyBatisParameterUtils {
/**
* in 参数分割
* @param wrapper
* @param column 检索字段
* @param coll 检索条件
* @param
* @param <T> 实例对象泛型
* @parma <F> 条件集合泛型
*/
public static <T,F> void cutInParameter (LambdaQueryWrapper<T> wrapper, SFunction<T,?> column,List<F> coll,String type){
if (CollectionUtils.isEmpty(coll)){
throw new Exception("参数为空");
}
if (coll.size <= 1000){
wrapper.in(column,coll);
return;
}
List<List<F>> lists = ListSplitUtils.spiltList(coll, 1000);
wrapper.and(item -> {
item.in(column, lists.remove(0));
for(List<F> objList : lists){
item.or().in(column, objList);
}
return item;
});
}
}
使用实例:
// Object泛指查询的实例对象
LambdaQueryWrapper<Object> wrapper = new LambdaQueryWrapper<>();
MybatisParameterUtils.cutInParameter(wrapper, Object::getId,idList);