如何在java代码中实现分批查询
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操作,继续封装
}
}
}
}
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: PHP构造JSon数据的两种方法
- 下一篇: java 分批次处理