Chr*_*her 6 java sql spring spring-data
我有一个名为“ImportReceiptRepository”的 Spring CrudRepository。
我只是想编写一个方法来获取 order by 子句中的第一行。
这是我目前正在使用的:
ImportReceipt importReceipt = this.importReceiptRepository.getOneByImportTypeOrderByTimestampDesc(importType);
Run Code Online (Sandbox Code Playgroud)
问题是,当返回多于一行时,Spring 会抛出:
org.springframework.dao.IncorrectResultSizeDataAccessException: result returns more than one elements; nested exception is javax.persistence.NonUniqueResultException: result returns more than one elements
Run Code Online (Sandbox Code Playgroud)
当返回 0-n 行时,我应该如何重命名这个 CrudRepository 函数以简单地获取第一行?
简单地使用 Pageable 是关键:
List<ImportReceipt> findByImportType(String importType, Pageable pageable);
Run Code Online (Sandbox Code Playgroud)
并称其为:
List<ImportReceipt> importReceipts = this.importReceiptRepository.findByImportType(importType, new PageRequest(0, 1, Direction.DESC, "Timestamp"));
ImportReceipt importReceipt = importReceipts.get(0);
Run Code Online (Sandbox Code Playgroud)
图片来源:如何在 Spring Data JPA 中将分页与条件查询结合起来?