我有一个包含32k行的大型Excel文件,以及一个将Excel数据持久化到mySQL数据库的Java代码。我的代码适用于大约6k行,但由于JPA限制,我的代码不能用于整个Excel。我读到它可以用JPA分页来完成,但是到目前为止,我只找到了从DB收集数据(已经持久化了数据)并呈现到UI的信息。Excel文件包含32k药物,这一行将持久化到DB中。
我使用以下方法创建了这个Controller层:
public ResponseEntity<ResponseMessage> uploadFile(@RequestParam("file") MultipartFile file,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "6000") int size) {
String message = "";
if (ExcelHelper.hasExcelFormat(file)) {
try {
// the following 6 row are my patetic attempt to resolve with pagination
List<Medicine> medicines = new ArrayList<>();
Pageable paging = PageRequest.of(page, size);
Page<Medicine> pageMedicamente = medicineRepositoryDao.save(paging);
medicines = pageMedicamente.getContent();
medicineService.save(file);
message = "Uploaded the file successfully: " + file.getOriginalFilename();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
} catch (Exception e) {
message = "Could not upload the file: " + file.getOriginalFilename() + "!";
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
}
}
以及储存层:
@Repository
public interface MedicineRepositoryDao extends JpaRepository<Medicine, Long> {
Page<Medicine> save( Pageable pageable);
}
还有服务层:
try {
List<Medicine> medicines = ExcelHelper.excelToMedicine(file.getInputStream());
medicineRepositoryDao.saveAll(medicines);
} catch (IOException e) {
throw new RuntimeException("fail to store excel data: " + e.getMessage());
}
}
发布于 2020-12-03 06:48:23
我觉得你把这事搞混了。
在这种情况下你有几个选择。
JdbcTemplate
或NamedParameterJdbcTemplate
来执行,而且速度要快得多,因为JPA的开销被跳过了,在这个场景中您也不会从中受益。如果您想使用ORM,您可能想看看Spring,它在概念上更简单,不保留对实体的引用,因此在这个场景中应该显示出更好的特性。我建议您不要在这里使用ORM,因为您似乎没有从实体中受益,所以创建实体然后让ORM从其中提取数据实在是浪费时间。JdbcTemplate
&Co),这对于32K行可能不是必需的,但可能会提高性能,并且在插入失败时可能对可恢复性有用。Spring批处理将帮助您实现该功能。虽然前面的点讨论了批处理,即将导入分解为块,但您还应该查看JDBC端的批处理,其中发送多个语句,或者一次发送多个参数集的单个语句到数据库,这同样应该改进performance.。
最后,
https://stackoverflow.com/questions/65116990
复制相似问题