1.前言
相信批量导入功能在许多应用场景都会使用到。本人在做一次公司需求时,因为需要校验Excel数据唯一性,所以代码变成了这样
for (BlackListInfoExcelDTO excelDTO : blackListInfoExcelDTOS) {
index = ++index;
BlackListInfoDTO dto = new BlackListInfoDTO();
BeanUtils.copyProperties(excelDTO, dto);
dto.setSuitBusiness(businessType);
this.saveBlackInfo(dto, loginUser);
}
每条数据插入时都要访问一遍数据库是否存在相同数据。那1000条数据就要访问1000次数据库,可知效率多低。
2.优化方案
思路:一次性将数据库所有数据查出来,然后与excel数据进行合并,最后再通过分组拿到分组后count>1的数据作为重复数据
代码如下:
List addList = new ArrayList<>();
List<BlackListInfoDO> all = this.list();
for (ExcelDTO excelDTO : ExcelDTOS) {
BlackListInfoDO entity = new BlackListInfoDO();
BeanUtils.copyProperties(excelDTO, entity);
SuitBusinessType businessType = (SuitBusinessType) this.getEnumByDisplayName(SuitBusinessType.class, excelDTO.getSuitBusiness());
entity.setSuitBusiness(businessType);
addList.add(entity);
all.add(entity);
}
Map<String, Long> countMap = all.stream().collect(Collectors.groupingBy(o -> o.getCustName() + o.getSuitBusiness().getDisplayName(), Collectors.counting()));
List result = countMap.entrySet().stream().filter(entry -> {
return entry.getValue() > 1;
}).collect(Collectors.toList());
result则为重复数据
3.后续优化(如果excel数据量过大,可通过批量方式进行savaBatch)