Friday, January 27, 2017

Spring: conversion of List to Page with pagination (PageImpl/Pageable)

Suppose you're retrieving via typedQuery some data.
You probably are getting a List<T> via getResultList() method(TypedQuery class).
Now you need to convert into into a Page<T> result, preserving pagination, obtained with page, size(, ecc.) parameters.....
In my case I solve it with this:
[....]
int pageNumber = 1 ;
int size = 1 ;
PageRequest page = new PageRequest(pageNumber, size);
List<Article> articlesList = articleTypedQuery.getResultList();
int start = page.getOffset();
int end = (start + page.getPageSize()) > articlesList .size() ? articlesList .size() : (start + page.getPageSize());       
int totalRows = articlesList .size();
Page<Article> pageToReturn = new PageImpl<Article>(articlesList .subList(start, end), page, totalRows); 


return pageToReturn;

That's all.....
Bye..