Tuesday, February 27, 2018

Paging and Sorting using Spring Boot

Picture Credit : Pixabay


Please follow Rest API Server to see the big picture and GitHub repo details.

Paging and Sorting is an important use case for any application. Any web or mobile frontend, a listing will usually need such a capability.

To support Paging and sorting in a Spring boot application, we need to do the following.

The Spring data repository interface


@Repository("groupRepository")
public interface GroupRepository extends PagingAndSortingRepository<Group, Long> {

}

In the service class, we should pass the pageable object to the findAll method. The Pageable object contains the details of which page of data to bring and how many records. Also what sort criteria to be applied. For example, you have 1000 records in db and based on name sorting, get the 26-50 records. So you can tell the Pageable object for the page to be 1 (with 0 indexing), size to be 25 (number of records) and sort to be done on name attribute with asc. The query that goes to the database takes care of this. The database will first sort and then return the records. The data is returned in a Page object which contains all the details including the total number of records.

public Page<GroupVO> getGroupVOPage(Pageable pageable){
Page<Group> groupList = groupRepository.findAll(pageable);
return toVOList(groupList);
}

How the Rest API looks like?

@RequestMapping(value="/group/list", method = RequestMethod.GET, produces = "application/json")
 @ApiImplicitParams({
@ApiImplicitParam(name = "page", dataType = "string", paramType = "query", defaultValue = "0",
               value = "Results page you want to retrieve (0..N)"),
@ApiImplicitParam(name = "size", dataType = "string", paramType = "query", defaultValue = "25",
                value = "Number of records per page."),
@ApiImplicitParam(name = "sort", allowMultiple = true, dataType = "string", paramType = "query",
                    value = "Direction of sort")
})
public ResponseEntity<Page<GroupVO>> getListOfGroup(Pageable pageable){
Page<GroupVO> groupVOPage = groupService.getGroupVOPage(pageable);
        return new ResponseEntity<>(groupVOPage, HttpStatus.OK);
}

Please note the ApiImplicitParams annotation. This is because of a bug in SpringFox which does not handle the RequestParam correctly. More details here

Now if we hit this API with the following details

http://localhost:8080/api/group/list?page=0&size=1&sort=name%2Casc

It returns

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

No comments:

Post a Comment