【发布时间】:2020-12-02 22:18:39
【问题描述】:
我有一个包含 32k 行的大型 Excel 文件,以及一个将 Excel 数据持久保存到 mySQL 数据库的 Java-Spring 代码。我的代码适用于大约 6k 行,但由于 JPA 限制,不适用于整个 Excel。我读到它可以用 JPA 分页来完成,但到目前为止,我只发现从 DB 收集数据(已经与数据一起保存)并呈现到 UI 的信息。 Excel 文件包含 32k 种药物,这些行将被持久化到数据库中。
我有这个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层:
@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());
}
}
【问题讨论】:
标签: java spring-boot jpa spring-data-jpa pagination