我正在以以下形式运行不同的JPA查询

Float getDepositVolumeByDepositIdDepositAndSpeciesIdSpeciesAndRangeIdRangeAndSubRangeIdSubrange(Long idDeposit, Long idSpecies, Long idRange, Long idSubRange); // this is one of the methods that fail
@Query("select stock.depositVolume from Stock s where s.deposit.idDeposit = ?1 and s.species.idSpecies = ?2 and s.range.idRange = ?3 and s.subrange.idSubrange = ?4")
Float getVolumeByDepositIdDepositAndSpeciesIdSpeciesAndRangeIdRangeAndSubRangeIdSubrange(Long idDeposit, Long idSpecies, Long idRange, Long idSubRange); // this one is just for ilustrative purpose and throws the exact same error



这两个查询只是应该返回一行的查询中的一部分。尽管数据库只有一行与提供给查询的数据相对应,但是hibernate会抛出以下错误消息:


结果返回多个元素


我已打开休眠查询日志,并且为第一种方法生成的查询如下:

select stock0_volume_stock as col_0_0_ from public.stock stock0_ where stock0_.id_deposit = ? and stock0_.id_species = ? and stock0_.id_range = ? and stock0_.id_sub_range = ?


具有正确绑定的参数。我在PostGres上运行查询,它只返回带有float的一行。

值得一提的是,我的课堂宣言是:

public interface StockRepository extends QueryDslPredicateExecutro<Stock>, JpaRepository<Stock, long>


我结束的工作就是将这些方法更改为

List<Stock> findFirstByDepositIdDepositAndSpeciesIdSpeciesAndRangeIdRangeAndSubRangeIdSubrange(Long idDeposit, Long idSpecies, Long idRange, Long idSubRange); // now it justly returns only one row, the first one


我通常以为,当然在以前的项目中,这是观察到的行为,第一种方法应该将从数据库中获取的唯一结果映射到预期的float

我对这种行为的解释很感兴趣。

最佳答案

如果您从WHERE表中选择某列... jpa / hibernate无法知道只有一行与条件匹配,相反,它必须假定返回了多行,而我猜是对于这样的查询,总是使用相同的逻辑(假设有多行),并且错误消息在这里会引起误解。

要获得一行,您将需要一个查询,该查询具有诸如SUM或COUNT之类的聚合函数作为SELECT子句中的唯一元素。也许很有趣,您可以尝试在原始查询中使用SUM,看看它是否返回预期的结果。

也许这比起回答更适合作为评论,但它似乎渴望评论

07-24 09:45
查看更多