java大数据量批量查询

场景:我们表里面有30w条数据,需要一次性全部查询出来肯定会非常的慢。如果批量查询呢

方法一:大多数人想到的是分页查询,如我每5000条数据分一次页,这样做百分百是可以实现的,但是会存在一个问题。如果表里面的数据量越大,这种方式会越慢,因为需要计算偏移量。

方法二:我们根据id来查询,前提是id是连续自增的。查询出总记录数,然后根据每次要取出的数据来计算应该需要取多少次。来循环的取出数据。

int total=300000; // 总记录数
int batchCount=5000; // 每次批量取的数据
int count=(int)Math.ceil((double)total/batchCount); // 向上取整

long maxId=1;
for(int h=0; h<count; h++){
    params.put("maxId", maxId);
    params.put("batchCount", batchCount);
    List<ProductMonth> productList=productMonthMapper.selectJmlProductInfo(params);
    if(null!=productList && productList.size()>0){
        for(int i=0; i<productList.size(); i++){
            long pid=productList.get(i).getId();
            if(i==productList.size()-1){ // 如果是最后一个id则赋值给maxId
                maxId=pid;
            }
            // 自己的业务处理。。。
        }
    }
}

xml查询的sql

<select id="selectJmlProductInfo" resultMap="BaseResultMap">
        select
            j.id, j.product_name, j.org_all_name, j.sales_num as salesNum, p.product_no
        from d_data_detail_jml j 
        where j.id > #{maxId} order by j.id limit #{batchCount}
</select>

https://www.91mszl.com/zhangwuji/article/details/1264

猜你喜欢

转载自blog.csdn.net/weixin_42415158/article/details/119596720