0

I am calling an external REST API and getting response as JSON array. I can implement pagination and sorting when saving and retrieving the same data from a database using JPA as shown below.

I am using H2 database and created below methods. Is it possible to do the same without using any database? Can we paginate and sort list of objects (created from JSON response) in a similar way?

public class APIResponse<T> {
    int recordCount;
    T response;
}
ResponseEntity<List<Person>> response=restTemplate.exchange(URL, HttpMethod.GET,null, new ParameterizedTypeReference<List<Person>>(){});
List<Person> persons=response.getBody();
personService.saveAllPersons(persons);
@GetMapping("/{field}")
private  APIResponse<List<Person>> getPersonsWithSort(@PathVariable String field){
    List<Person> personsSorted = personService.findPersonsWithSorting(field);
    return new APIResponse<>(personsSorted.size(),personsSorted);
}

@GetMapping("/pagination/{offset}/{pageSize}")
private  APIResponse<Page<Person>> getPersonsWithSort(@PathVariable int offset, @PathVariable int pageSize){
    Page<Person> personsPaginated = personService.findPersonsWithPagination(offset, pageSize);
    return new APIResponse<>(personsPaginated.getSize(),personsPaginated);
}

@GetMapping("/pagination/{offset}/{pageSize}/{field}")
private  APIResponse<Page<Person>> getPersonsWithSort(@PathVariable int offset, @PathVariable int pageSize,@PathVariable String field){
    Page<Person> personsPaginated = personService.findPersonsWithPaginationSorting(offset, pageSize,field);
    return new APIResponse<>(personsPaginated.getSize(),personsPaginated);
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Philsearo
  • 27
  • 3
  • 1
    It's unclear to me what you're stuck with. Since the response of your API is an array, you should be able to [sort the list by some property](https://stackoverflow.com/q/5805602/1915448) and [filter out a range of items](https://stackoverflow.com/q/22917270/1915448). Is this what you're looking for? – g00glen00b Aug 01 '22 at 23:18
  • Yes, it can be done without a database. You will only have data in memory if you don't use a database. When your service goes down the data disappears. Pagination on the middle tier is inefficient: you bring all those bytes into a collection on the middle tier, only to filter it down to a single page. Wasteful of network, memory, and CPU. – duffymo Aug 02 '22 at 12:42

0 Answers0