Boost performance of pagination with infinite scrolling using Slice

Pagination with infinite scrolling is using Spring Data Page to retrieve entities from your database. This will trigger two queries, one to fetch entities and second for count all to determine the total items for paging. Infinite scrolling doesn’t need information about the total size but only if there is a next page to load. To avoid count all query which can be an expensive operation when working with large datasets, use Slice instead of Page which will boost performance of infinite scrolling.

We will use a custom HTTP header X-Has-Next-Page to send information to front-end infinite-scroll plugin.

Define new method in your Entity repository:

Slice<YourEntity> findSliceBy(Pageable pageable);

Define new static method in PaginationUtil.java located in web/rest/util package

public static HttpHeaders generateSliceHttpHeaders(Slice<?> slice) {
  HttpHeaders headers = new HttpHeaders();
  headers.add("X-Has-Next-Page", "" + slice.hasNext());
  return headers;
}

Modify REST controller to call Slice instead of Page and generate new HTTP headers.

@GetMapping("/<YourEntities>")
@Timed
public ResponseEntity<List<Repo>> getAllRepos(Pageable pageable)
    throws URISyntaxException {
    Slice<YourEntity> slice = repoRepository.findSliceBy(pageable);
    HttpHeaders headers = PaginationUtil.generateSliceHttpHeaders(slice);
    return new ResponseEntity<>(slice.getContent(), headers, HttpStatus.OK);
}

Define new view model in entity.controller.js

vm.hasNextPage = false;
Extract HTTP header value from response and assign it to view model in
function onSuccess(data, headers) {
    vm.hasNextPage = headers('X-Has-Next-Page') === "true";
    ...
}

Use view model with infinite-scroll plugin in .html

<tbody infinite-scroll="vm.loadPage(vm.page + 1)" infinite-scroll-disabled="!vm.hasNextPage">
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值