This is related to this question: Total row count for pagination using JPA Criteria API.
I do not want to do two separate queries, one for select the count then one to get the paginated results. Is there a way to do that?
If your strictly just using criteria builder you will need a separate query to get the total count.
If you do want to avoid using two database queries you can use the findAll()
method and pass in specification and pageable. Within the your Specification class you can put your criteria builder logic and within pageable you can define page size, page number and sorting.
And then you can cast your results to a page of your object i.e. Page<YourObject> myPage
. and you can simply get your results back doing myPage.getTotalElements();