SQL查询in大于1000处理

近期在代码开发中,发现某些业务场景因为多个服务的调用查询,避免不了使用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);
  • 9
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值