13

Is there possibility to use limit or setMaxResults using Spring-Data-JPA Specification? I can use it via Criteria or JPQL, but I need only via specifications. Specifications have CriteriaQuery, not a Query. So, there is no setMaxResults method.

Squeez
  • 919
  • 2
  • 12
  • 30
  • 1
    Possible duplicate of [Select top 1 result using JPA](http://stackoverflow.com/questions/6708085/select-top-1-result-using-jpa) – acm Mar 15 '17 at 08:49
  • @acm no, specifications have `CriteriaQuery`, that does not have `setMaxResults`. That's not a duplicate. – Squeez Mar 15 '17 at 08:53
  • is [this](http://stackoverflow.com/questions/9314078/setmaxresults-for-spring-data-jpa-annotation) helpful? – acm Mar 15 '17 at 09:06
  • @acm no, I saw this. I didn't find my answer on stackverflow. – Squeez Mar 15 '17 at 09:12
  • Well, could post an code example of what you are trying? – acm Mar 15 '17 at 09:37

1 Answers1

23

I think you only have two options:

Use Pageable with your Specification:

Pageable limit = new PageRequest(0,10);
repo.findAll(spec, limit);

or do a workaround like this one: https://gist.github.com/tcollins/0ebd1dfa78028ecdef0b. All the credits to @tcollins

Cleto Gadelha
  • 1,083
  • 9
  • 14
  • i am using already "sort" instead PageReuest. there is no parameter for sort AND PagerRequest? – d2k2 Nov 06 '18 at 17:38
  • 6
    PageRequest has a constructor with Sort. You can use it. – Cleto Gadelha Nov 06 '18 at 19:42
  • 2
    Beware that this would still query the total count from DB: [How to disable count when Specification and Pageable are used together?](https://stackoverflow.com/questions/26738199/how-to-disable-count-when-specification-and-pageable-are-used-together) – Vadzim Sep 22 '21 at 21:58