【问题标题】:Spring JPA Query for fetching latest records in a Table用于获取表中最新记录的 Spring JPA 查询
【发布时间】:2015-08-26 07:42:05
【问题描述】:

我是 Spring JPA 的新手。我有一个名为 Product 的模型。我正在尝试编写一个 api 端点来获取 products 表的最近记录。

public static interface Repository extends PagingAndSortingRepository<Product, Long>
   {
      List findTop2ByOrderByIdDesc();
   }

当我运行我的应用程序 HAL 浏览器时 http://localhost:8080/api/v1/products/search/findTop2ByOrderByIdDesc

我得到的错误是

{
  "timestamp": 1440573947629,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "org.springframework.dao.IncorrectResultSizeDataAccessException",
  "message": "result returns more than one elements; nested exception is javax.persistence.NonUniqueResultException: result returns more than one elements",
  "path": "/api/v1/products/search/findTop2ByOrderByIdDesc"
}

如何解决这个问题。请指教

【问题讨论】:

  • 发布您的模型和控制器代码,可能是它调用您的其他代码。通常你的代码看起来不错。还要提供您正在使用的数据库。

标签: spring spring-data spring-data-jpa hal


【解决方案1】:
List findTop2ByOrderByIdDesc();

在这里,您告诉 JPA 您期望“findTop2ByOrderByIdDesc()”方法返回一个“List”类型的对象。 findTop2ByOrderByIdDesc() 实际上要返回的是 List。

所以,只需将“List findTop2ByOrderByIdDesc()”更改为“List&lt;Product&gt; findTop2ByOrderByIdDesc()

【讨论】:

    猜你喜欢
    • 2021-08-24
    • 2014-07-26
    • 1970-01-01
    • 2021-10-17
    • 2016-10-15
    • 2011-10-26
    • 1970-01-01
    • 2017-11-19
    • 2022-01-06
    相关资源
    最近更新 更多