牛骨文教育服务平台(让学习变的简单)
博文笔记

如何在java代码中实现分批查询

创建时间:2017-09-11 投稿人: 浏览次数:1674
package com.h.collection;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by John on 2017/9/11.
 */
public class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("1");
        list.add("2");
        list.add("3");
        String str = String.join(",",list);
        System.out.println(str);
    }

    /**
     * 批量查询/插入
     * 查询数据量非常大时,分批查,减轻数据库一次查询的压力
     * @param userIdList 用户ID的集合
     */
    public static void batchSelect(List<String> userIdList){
        int totalSelectCount = userIdList.size();//总查询量
        int perSelectCount = 1000;//每次查询的数据量
        int index = 0;//查询中间量
        List<String> selectList = null;
        List<User> userList = null;
        while (totalSelectCount > index){
            int selectCount = Math.min(totalSelectCount,index + perSelectCount);
            selectList = userIdList.subList(index,selectCount);//查询范围[index,selectCount-1];
            userList = userServiceImpl.batchSelectUserById(String.join(",",selectList));
            for (User user:userList){
                //其他set操作,继续封装
            }
            index += perSelectCount;
        }
    }

    /**
     * 批量查询/插入
     * 查询数据量非常大时,分批查,减轻数据库一次查询的压力
     * @param userIdList
     */
    public static void batchSelect2(List<String> userIdList){
        int totalSelectCount = userIdList.size();//总查询量
        int perSelectCount = 1000;//每次查询的数据量
        int cycleCount = totalSelectCount % perSelectCount == 0 ? totalSelectCount/perSelectCount:totalSelectCount/perSelectCount + 1;//循环查询次数
        List<String> selectList = null;
        List<User> userList = null;
        for (int i=0;i<cycleCount;i++){
            //[0,999] [1000,1999] ... 这里用到了分页的思想
            selectList = userIdList.subList(i*perSelectCount,(i+1)*perSelectCount > totalSelectCount ? totalSelectCount:(i+1)*perSelectCount);//[,)
            userList = userServiceImpl.batchSelectUserById(String.join(",",selectList));
            for (User user:userList){
                //其他set操作,继续封装
            }
        }
    }
}
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。