java 如何使用过滤器进行分页

uxhixvfz  于 2023-01-11  发布在  Java
关注(0)|答案(1)|浏览(290)

我想使用筛选器创建可分页服务,但无法创建结果集
这是我的控制器

@GetMapping(path = "/PageFilter")
    public DataResponsePagination<HistoryBankWrapper, HistoryBank> pageFilter(
        @RequestParam("filter") String keyfilter ,
        @RequestParam("sortField") String field ,
        @RequestParam("sortOrder") String order ,
        @RequestParam("page") int page, 
        @RequestParam("size") int size) {
        return new DataResponsePagination<HistoryBankWrapper, HistoryBank>(historyBankService.findByFilter(keyfilter,field,order, page, size));
    }

这是我的服务

public PaginationList<HistoryBankWrapper, HistoryBank> findByFilter(String keyfilter,String sortField,String sortOrder, int page, int size) {
    Pageable paging = PageRequest.of(page, size);
    Page<HistoryBank> historyPage = historyBankRepository.findAllFilter(keyfilter, sortField, sortOrder, paging);
    List<HistoryBank> historyList =  historyPage.getContent();
    List<HistoryBankWrapper> historyWrapperList = toWrapperList(historyList);
    return new PaginationList<HistoryBankWrapper, HistoryBank>(historyWrapperList, historyPage);
    }

这是我存储库

@Query(value = "SELECT * FROM HISTORY_BANK WHERE :sortField LIKE '%' || :keyFilter || '%' ORDER BY :sortField :sortOrder",
          countQuery = "SELECT count(*) FROM HISTORY_BANK",
          nativeQuery = true)
Page<HistoryBank> findAllFilter(@Param("keyFilter") String keyfilter,  @Param("sortOrder") String sortOrder,@Param("sortField") String sortField, @Param("paging") Pageable paging);
fafcakar

fafcakar1#

抛弃你自己的方法,使用框架。使用规范来创建动态查询。
存储库应该扩展JpaSpecificationExecutor,然后从服务调用findAll(Specification, Pageable),服务应该准备构建查询所需的Specification

public interface YourRepository extends JpaRepository<HistoryBank, Long>,
JpaSpecificationExecutor<HistoryBank> {}

然后,您的服务可以使用前面提到的findAll方法。

public PaginationList<HistoryBankWrapper, HistoryBank> findByFilter(String keyfilter,String sortField,String sortOrder, int page, int size) {
    Sort sort = Sort.by(Sort.Direction.fromString(sortOrder), sortField); 
    Pageable paging = PageRequest.of(page, size);
    Specification<HistoryBank> spec = (r, c, b) -> b.like(r.get(sortField), "%" + keyFilter + "%"));
    Page<HistoryBank> historyPage = historyBankRepository.findAllFilter(spec, paging);
    List<HistoryBank> historyList =  historyPage.getContent();
    List<HistoryBankWrapper> historyWrapperList = toWrapperList(historyList);
    return new PaginationList<HistoryBankWrapper, HistoryBank>(historyWrapperList, historyPage);
    }

您甚至可以通过修改控制器使其直接绑定到Pageable对象来简化此操作,这样就不必创建它。

public DataResponsePagination<HistoryBankWrapper, HistoryBank> pageFilter(
        @RequestParam("filter") String keyfilter ,
        Pageable page) {
        {

现在,您只需要创建Specification,然后沿着Pageable即可。

相关问题