Search code examples
springspring-dataspring-data-jpahal

Spring JPA Query for fetching latest records in a Table


I am new to Spring JPA. I have a model in the name of Product. I am trying to write an api end point for fetching the recent records of the products table.

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

When i run my application HAL Browser http://localhost:8080/api/v1/products/search/findTop2ByOrderByIdDesc

I am getting the error as

{
  "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"
}

How to fix this. Kindly advise


Solution

  • List findTop2ByOrderByIdDesc();
    

    Here you are telling the JPA that you are expecting an object of type "List" to be returned by the method "findTop2ByOrderByIdDesc()". What actually is going to be returned by findTop2ByOrderByIdDesc() is List.

    So, just change "List findTop2ByOrderByIdDesc()" to "List<Product> findTop2ByOrderByIdDesc()"