今天在mybatis做批量插入操作的时候要考虑一个问题,就是在集合长度达到200的时候操作一次批量插入,因为数据太多对于mysql会有压力,所以就对集合做了一个分片功能,话不多说,上代码;
/**
*
* @param sourceList 原集合
* @param subListSize 分割后子集合长度
* @param <T>
* @return 以Map格式存放的子list集合 key是第几段 value是子集合
*/
public static <T> Map<Integer, List<T>> splitList(List<T> sourceList, int subListSize) throws Exception {
if(CollectionUtils.isEmpty(sourceList)){
throw new Exception("source list can not be null!");
}
if(subListSize <= 0){
throw new Exception("sub list size can not be zero!");
}
if(sourceList.size() < subListSize){
throw new Exception("sub list list size can not be longer than source size!");
}
//集合长度
int size = sourceList.size();
//分片数
int segment