Skip to content

Instantly share code, notes, and snippets.

@ufuk
Last active February 8, 2021 13:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ufuk/49cf74f6805b8c62f6ca44911f0526b3 to your computer and use it in GitHub Desktop.
Save ufuk/49cf74f6805b8c62f6ca44911f0526b3 to your computer and use it in GitHub Desktop.
SpringDataPageUtils to convert paged entities to paged model objects
import org.springframework.data.domain.Page;
import org.springframework.data.support.PageableExecutionUtils;
import java.util.function.Function;
import java.util.stream.Collectors;
public final class SpringDataPageUtils {
public static <T, C> Page<C> convertPage(Page<T> page, Function<T, C> converter) {
return PageableExecutionUtils.getPage(
page.getContent()
.stream()
.map(converter)
.collect(Collectors.toList()),
page.getPageable(),
page::getTotalElements
);
}
}
Page<Product> page = productRepository...;
Page<ProductModel> convertedPage = SpringDataPageUtils.convertPage(page, eachProduct -> {
ProductModel productModel = new ProductModel();
productModel.setId(eachProduct.getId());
...
return productModel;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment