简体   繁体   中英

IncorrectResultSizeDataAccessException - Trying to simply get the most recent row

I have a Spring CrudRepository called 'ImportReceiptRepository'.

I'm simply trying to compose a method which grabs the first row in an order by clause.

Here's what I'm using currently:

ImportReceipt importReceipt = this.importReceiptRepository.getOneByImportTypeOrderByTimestampDesc(importType);

The issue is that when there is more than a single row returned, Spring throws a:

org.springframework.dao.IncorrectResultSizeDataAccessException: result returns more than one elements; nested exception is javax.persistence.NonUniqueResultException: result returns more than one elements

How should I rename this CrudRepository function to simply grab the first row when there are 0-n rows returned?

Simply using Pageable was the key:

List<ImportReceipt> findByImportType(String importType, Pageable pageable);

and calling it like:

List<ImportReceipt> importReceipts = this.importReceiptRepository.findByImportType(importType, new PageRequest(0, 1, Direction.DESC, "Timestamp"));
ImportReceipt importReceipt = importReceipts.get(0);

Credit: How to combine pagination with a criteria query in Spring Data JPA?

As of the upcoming version 1.7 of Spring Data JPA, the query method as you originally declared it works out of the box. See this ticket for details. The support has already been published in the first milestone of the release.

You can make it even simpler by findFirst:

ImportReceipt findFirstByImportType(String importType);

For more info: Limiting Query Results

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM