Fetching only first/last element using Spring Data JPA and @Query annotation

Ueli Hofstetter picture Ueli Hofstetter · Sep 8, 2015 · Viewed 28.9k times · Source

EDIT: Solutions to this problem are provided in the second and fourth answer regarding this question setMaxResults for Spring-Data-JPA annotation?

Goal: Fetch the largest/smallest element by property z using a Spring Data JPA repository and the Spring Query annotation.

What I have so far

@Query("SELECT xelement FROM x xelement ORDER BY xelement.z")
public List<X> findFirstElement();

Problem: This query fetches all elements (which is not really effective). If I would use the EntityManager direcly, I could set the number of results using

entityManager.setMaxResults(1)

to only get the first element.

Question: How do I specify the maximum number of results using the @Query annotation?

Idea: Is using a PageRequest of size 0 the way to go?

Constraints: I am aware of the "FindFirstBy...." query feature but I want/have to use the @Query annotation.

Answer

ahmetcetin picture ahmetcetin · Jun 15, 2017

You can use the limit property of sql just by adding nativeQuery to @Query annotation. However, there is another and a better way of doing this. Pageable class in your repository method will solve your problem without touching your @Query annotation:

@Query(value = "SELECT xelement FROM x xelement ORDER BY xelement.z")
List<X> findFirstElement(Pageable limit);

To set the limit and offset, use should call this repository method as follows:

List<X> xValues = xRepository.findFirstElement(new PageRequest(0, 1));

Here 1 corresponds to the limit which you want.

UPDATE (SPRING DATA 2.0)

Use PageRequest.of(0, 1) instead of new PageRequest(0, 1)