Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data Hibernate + Pageable: Returns empty results

I am using Spring Data repositories without any problems. When I tried to add Paging (using the Pageable interface) it worked OK.

However, when the returned result set is less then the Page size, the result is empty List.

The following is my PageRequest. The default values for index and objectsPerPage are 0 and 10 respectively.

new PageRequest(pageIndex_, objectsPerPage_, new Sort(orders))

When using it with a query that returns less than 10 results, the resulting list is empty.

This is how I use the repository in the Service layer:

repository.findAll(MySpecification.searchClients(criteria),
            myPagingSpecification(criteria.getPageIndex(), criteria.getNumberPerPage(), null))
            .getContent();

EDIT 1 I found the cause of this, however I am still searching for a solution or a workaround.

        Long total = QueryUtils.executeCountQuery(getCountQuery(spec));
    List<T> content = total > pageable.getOffset() ? query.getResultList() : Collections.<T> emptyList();

This code, located in the SimpleJpaRepository class makes select count... and if the count is less then the offset, returns an empty list.

like image 697
m.mitropolitsky Avatar asked May 27 '15 13:05

m.mitropolitsky


1 Answers

According to PageRequest implementation:

public int getOffset() {
    return page * size;
}

so if you set page to 0 the offset value must also be 0 and cannot be larger than total (if total > 0).

Check (maybe in debugger) what pageIndex value you pass to spring-data. It may be other value - sometimes it is simple mistake.

like image 150
przemek hertel Avatar answered Oct 16 '22 05:10

przemek hertel