Home > front end >  Spring Boot Pagination - PagingAndSortingRepository not returning any results
Spring Boot Pagination - PagingAndSortingRepository not returning any results

Time:10-04

I've created a PagingAndSortingRepository in Spring Boot, but it does not return any results (thought it should).

The repository:

@Repository
public interface DoctorPagingRepository extends PagingAndSortingRepository<Doctor, Integer> {

    Page<Doctor> findByName(String name, Pageable pageable);
    Page<Doctor> findAllByUsername(String username, Pageable pageable);
    Page<Doctor> findAllByName(String name, Pageable pageable);
    Page<Doctor> findAllByNameContaining(String name, Pageable pageable);
}

I have other repositories which work, when not using Pageable methods i.e.

@Repository
public interface UserPagingRepository extends PagingAndSortingRepository<User, Integer> {
    User findByUsername(String username);
    User findByEmail(String email);
}

But anytime I attempt to user pageable repository methods it does work:

    @GetMapping("get-doctor/name/{name}/{pageNum}")
    public JsonResponse findDoctorByFirstname(@PathVariable String name, @PathVariable String pageNum) {
        //set page number and return up to 10 elements
        Pageable page = PageRequest.of(Integer.parseInt(pageNum), 10);

        //get list of users from that page
        Page<Doctor> doctorPage = userServices.getDoctorPaging().findAllByNameContaining(name, page);

        //set response object with users
        DoctorListResponse res = new DoctorListResponse();
        try {
            doctorPage.getContent().forEach( u -> {
                logger.trace(u.toString());
                res.getDoctorJsons().add(new DoctorJson(u));
                res.setSuccess(true);
            });
         } catch (Exception e) {
             res.setSuccess(false);
         }
         
         res.setTotalPages(doctorPage.getTotalPages());
         return res;
    }

Can anyone see where this might be going wrong?

CodePudding user response:

It turned out that the problem was to do with PageRequest.of() method's first parameter page is 'zero based page index', which I didn't realise. So it was returning the second page of results when pageNum was set to 1. The second page was empty as only 5 results in the database could have matched my query would be on the first page (as each page was set to hold ten results).

The solution was just to -1 from the pageNum:

Pageable page = PageRequest.of(Integer.parseInt(pageNum)-1, 10);

  • Related