useranon
useranon

Reputation: 29514

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

Upvotes: 1

Views: 10901

Answers (1)

Harley
Harley

Reputation: 562

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()"

Upvotes: 6

Related Questions