关于Mybatis-Plus中in超过一千处理方式

在mysql和oracle查询中, 使用in条件拼接数据超过一千时, 数据库会报错,为了避免出现数据库报错,需要手动拆分数据, 拼接数据达到in() or in()…的效果, 其中mybatis中的拼接主要是在xml文件中处理,而Mybatis-Plus则可以提供统一的工具类进行处理.

1 在xml中处理sql

1 切割集合

方法一:

List<Integer>  list =new ArrayLiat();
List<List<Integer>> list1 = ListUtils.partition(list, 999);

方法二:

private List<List<Integer>> splitList(List<Integer> list, int len) {

List<List<Integer>> result = new ArrayList<List<Integer>>();
int size = list.size();
int count = (size + len - 1) / len;
for (int i = 0; i < count; i++) {
List<String> subList = list.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
result.add(subList);
}
return result;
}

2 拼接数据

通过两次遍历,达到id in (xx,xx,…) or id in (xx,xx,…)

WHERE id IS NOT NULL
<if test="userids!=null and userids.size()>0" >
and
<foreach collection="userids" item="userid" open="(" separator="or" close=")">
id in
<foreach collection="userid" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</foreach>
</if>

2 Mybatis-plus中解决方案

一般可以归纳为工具类

public class MybatisParameUtils{
    // 查询QueryWrapper
    public static <T, F> void cutInParameByQuery(LambdaQueryWrapper<T> wrapper, SFuncion<T, ?> column, List<F> oldList){
        // 拆分list
        List<List<F>> newList = Lists.partition(oldList, 999);
        
        if(CollectionUtil.isEmpty(newList)){
            throw new Exception("集合为空");
        }else if(1 == newList.size()){
            wrapper.in(column, newList.get(0));
            return;
        }
        
        wrapper.and(i ->{
            for(List<F> list: newList){
                i.or().in(column, list);
            }
        })
    }
    
    
    // 更新UpdateWrapper
    public static <T, F> void cutInParameByUpdate(LambdaUpdateWrapper<T> wrapper, SFuncion<T, ?> column, List<F> oldList){
        // 拆分list
        List<List<F>> newList = Lists.partition(oldList, 999);
        
        if(CollectionUtil.isEmpty(newList)){
            throw new Exception("集合为空");
        }else if(1 == newList.size()){
            wrapper.in(column, newList.get(0));
            return;
        }
        
        wrapper.and(i ->{
            for(List<F> list: newList){
                i.or().in(column, list);
            }
        })
    }
    
}
  • 15
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值