简体   繁体   English

IncorrectResultSizeDataAccessException - 尝试简单地获取最新的行

[英]IncorrectResultSizeDataAccessException - Trying to simply get the most recent row

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函数来简单地获取第一行?

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? Credit: 如何在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. 从即将发布的Spring Data JPA 1.7版本开始,您最初声明的查询方法开箱即用。 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: 你可以通过findFirst使它变得更简单:

ImportReceipt findFirstByImportType(String importType);

For more info: Limiting Query Results 有关详细信息: 限制查询结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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