目录
1.背景
批量插入通过sql拼接插入数据,可以提高插入效率。
当数据量过大,mysql有max_allowed_packet 参数限制。
需要分批次插入,比如10000条数据,分为10次,一次插入1000条。
2.批次工具类实现SqlUtil
public class SqlUtil {
private SqlUtil() {
}
/**
* 分批次批量插入
* @param list 全量数据
* @param batchSize 批次插入大小
* @param consumer 插入处理
* @param <E>
*/
public static <E> void batchInsert(List<E> list, int batchSize, Consumer<List<E>> consumer) {
if (list == null || list.isEmpty()) {
return;
}
List<E> insertList = Lists.newArrayList();
int size = list.size();
int idxLimit = Math.min(batchSize, size);
int i = 1;
for (Iterator<E> item = list.iterator(); item.hasNext(); ++i) {
E element = item.next();
insertList.add(element);
if (i == idxLimit) {
consumer.accept(insertList);
insertList.clear();
idxLimit = Math.min(idxLimit + batchSize, size);
}
}
}
}
3.使用
在工具类里面使用批量插入,设置好每次插入数量。
每次插入1000条,根据公司业务可以调整。
@Service
public class UserServiceImpl {
@Resource
private UserMapper userMapper;
public void batchInsert(List<UserInfo> addUserInfoList){
SqlUtil.batchInsert(addUserInfoList, 1000, (insertList) -> {
userMapper.batchInsert(insertList);
});
}
}