Home > Software design >  Pagination in spring does not work when i use findAllBy Containing and Ignore Case?
Pagination in spring does not work when i use findAllBy Containing and Ignore Case?

Time:02-11

Can someone explain to me why my code wont work? I'm trying to create an endpoint that searches for a recipe by name.

When I try to return a list, my code works. It returns the correct search result:

@ResponseStatus(HttpStatus.OK)
@GetMapping(path = "api/v1/recipe", params = {"page", "size", "name"})
public List<Recipe> fetchAllRecipes(
    @RequestParam(name = "page", required = true) Integer page,
    @RequestParam(name = "size", required = true) Integer size,
    @RequestParam(name = "name", required = true) String name
) {
    return recipeRepository.findAllByNameContainingIgnoreCaseAndStatus(name, RecipeStatus.UPDATED);
}    

However when I try to paginate it, the content is always empty:

@ResponseStatus(HttpStatus.OK)
@GetMapping(path = "api/v1/recipe", params = {"page", "size", "name"})
public Page<Recipe> fetchAllRecipes(
    @RequestParam(name = "page", required = true) Integer page,
    @RequestParam(name = "size", required = true) Integer size,
    @RequestParam(name = "name", required = true) String name
) {
    Pageable pageRequest = PageRequest.of(page, size, Sort.Direction.ASC, "id");
    return recipeRepository.findAllByNameContainingIgnoreCaseAndStatus(name, RecipeStatus.UPDATED, pageRequest);
}

Response:

{
  "content": [],
  "pageable": {
    "sort": {
      "sorted": true,
      "unsorted": false,
      "empty": false
    },
    "pageNumber": 1,
    "pageSize": 10,
    "offset": 10,
    "paged": true,
    "unpaged": false
  },
  "last": true,
  "totalPages": 1,
  "totalElements": 2,
  "first": false,
  "sort": {
    "sorted": true,
    "unsorted": false,
    "empty": false
  },
  "number": 1,
  "numberOfElements": 0,
  "size": 10,
  "empty": true
}

Here are the dependencies I'm using:

    'org.springframework.boot:spring-boot-starter'
    'org.springframework.boot:spring-boot-starter-web'
    'org.springframework.boot:spring-boot-starter-data-jpa'
    'org.springframework.boot:spring-boot-starter-test'

CodePudding user response:

The page index of the PageRequest is zero-based, which is why all 2 existing elements will be on page 0 and page 1 is empty.

https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/domain/PageRequest.html#of-int-int-org.springframework.data.domain.Sort-

  • Related