我想在我的网站上启用“加载更多”功能。 由于我使用Spring JPA从远程数据库中获取数据,我想知道如何在Spring中实现这样的功能?
基本上,我想要做的是在第一个REST呼叫上只加载100条记录。如果用户点击“Load More”,那么我会对我停止的最后一个索引的另外100条记录执行新的调用(表示记录 101-200),依此类推。
如果需要,我可以通过HTTP POST发送开始和结束索引。这是我的存储库:
@Repository
public interface IStatusRepository extends CrudRepository<StatusDAO,String> {
List<StatusDAO> getStatusByIdAndFqhnIn(String id, List<String> filteredHostList);
}
你有什么建议吗?
分析解答
您可以使用Pageable
或PagingAndSortingRepository<T, ID>
来满足您的要求。
通过扩展PagingAndSortingRepository,
我们get f indAll(Pageable pageable)
和findAll(Sort sort)
方法进行分页和sorting。
一旦我们从PagingAndSortingRepository扩展了我们的存储库,我们只需要:
- 创建或获取PageRequest对象,这是一个实现 Pageable界面
- 将PageRequest对象作为参数传递给存储库方法 我们打算用
例:
public interface ProductRepository extends PagingAndSortingRepository<Product, Integer> {
List<Product> findAllByPrice(double price, Pageable pageable);
}
Pageable firstPageWithTwoElements = PageRequest.of(0, 2);
Pageable secondPageWithFiveElements = PageRequest.of(1, 5);
Page<Product> allProducts = productRepository.findAll(firstPageWithTwoElements);
List<Product> allTenDollarProducts =
productRepository.findAllByPrice(10, secondPageWithFiveElements);