Query in Repository With Limit

Spring Data JPA Custom Query limit functionality not working

Try to pass a method parameter with type Pageable:

@Query("select q from SecurityQuestion q order by q.questionId asc")
public List<SecurityQuestion> findQuestion(Pageable page);

and when you call this function, init page like this:

securityQuestionRepository.findQuestion(new PageRequest(0, 3));

Or just use native query:

@Query(nativeQuery = true,
value = "select * from user_security_question order by question_id asc limit 0, 3")
public List<SecurityQuestion> findQuestion();

Spring Boot CrudRepository or JpaRepository - how to pass limit as argument?

From spring doc (Limiting query results):

The results of query methods can be limited via the keywords first or top, which can be used interchangeably. An optional numeric value can be appended to top/first to specify the maximum result size to be returned. If the number is left out, a result size of 1 is assumed.

So, for fixed limit N you can use List<Example> findTopNByValidIsTrue()

For variable value of limit you should use Pageable:

Page<Example> findByValidIsTrue(Pageable pageable);
List<Example> result = repository.findByValidIsTrue(new PageRequest(0, N)).getContent();


Related Topics



Leave a reply



Submit