java IncorrectResultSizeDataAccessException - 试图简单地获取最近的行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25454582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:03:59  来源:igfitidea点击:

IncorrectResultSizeDataAccessException - Trying to simply get the most recent row

javasqlspringspring-data

提问by Christopher

I have a Spring CrudRepository called 'ImportReceiptRepository'.

我有一个名为“ImportReceiptRepository”的 Spring CrudRepository。

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

我只是想编写一个方法,该方法可以在 order by 子句中获取第一行。

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:

问题是当返回多于一行时,Spring 会抛出:

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?

当返回 0-n 行时,我应该如何重命名这个 CrudRepository 函数以简单地获取第一行?

回答by Christopher

Simply using Pageable was the key:

简单地使用 Pageable 是关键:

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?

信用:如何在 Spring Data JPA 中将分页与条件查询结合起来?

回答by Oliver Drotbohm

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 ticketfor details. The support has already been published in the first milestone of the release.

从即将发布的 Spring Data JPA 1.7 版开始,您最初声明的查询方法开箱即用。详情请参阅这张票。该支持已在该版本的第一个里程碑中发布。

回答by liranfar89

You can make it even simpler by findFirst:

你可以通过 findFirst 让它变得更简单:

ImportReceipt findFirstByImportType(String importType);

For more info: Limiting Query Results

更多信息:限制查询结果