Spring JPA Query用于获取表中的最新记录

use*_*non 1 spring hal spring-data spring-data-jpa

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

public static interface Repository extends PagingAndSortingRepository<Product, Long>
   {
      List findTop2ByOrderByIdDesc();
   }
Run Code Online (Sandbox Code Playgroud)

当我运行我的应用程序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"
}
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题.好心提醒

Har*_*ley 5

List findTop2ByOrderByIdDesc();
Run Code Online (Sandbox Code Playgroud)

在这里,您告诉JPA您期望通过方法"findTop2ByOrderByIdDesc()"返回"List"类型的对象.findTop2ByOrderByIdDesc()实际返回的是List.

所以,只需将" List findTop2ByOrderByIdDesc()" 更改为" List<Product> findTop2ByOrderByIdDesc()"