【问题标题】:Spring Data JDBC - Pageable on custom QuerySpring Data JDBC - 可在自定义查询上分页
【发布时间】:2020-11-23 20:16:16
【问题描述】:

在我的项目中,我有一个扩展 CrudRepository 的存储库。在里面我有一个自定义查询:

    public interface CustomerRepository extends CrudRepository<Customer, Long> {
       @Query("select * from person where firstname = :firstname")
       List<Customer> findByFirstname(@Param("firstname") String firstname, Pageable pageable);
    }

在我的服务类中,我尝试将列表放入可分页的对象中,例如:

... getPageableCustomer(String firstname, Pageable pageable){
// => By using "Sol" I got 90 matching entries 
List<Customer> custList = customerRepository.findByFirstname(firstname, pageable);

Page<Customer> custPage = new PageImpl<Customer>(custList, pageable, custList.size());

return custPage;
}

返回值包括完整的列表“custList”。获取具有指定偏移量和大小的可分页对象的最佳方法是什么?

一种选择是使用

customer.subList(fromIndex, toIndex)

但这感觉不对。也因为加载了列表中的所有数据,而不是仅仅通过可分页参数化的大小和偏移量获取数据。

备注:如果在 Repository 中使用 Page,我会得到 org.springframework.dao.IncorrectResultSizeDataAccessException: Incorrect result size: expected 1, actual 88

这里还有一个关于 Jira 的开放改进: https://jira.spring.io/browse/DATAJDBC-554?filter=-3

希望得到一些帮助...

【问题讨论】:

    标签: spring-boot spring-data-jdbc pageable


    【解决方案1】:

    我收到了 Dirk Luijk (Thx Dirk :)) 对 JIRA 问题的回复

    https://jira.spring.io/browse/DATAJDBC-554?filter=-3

    interface FooRepository extends PagingAndSortingRepository<FooEntity, Long> {
        List<FooEntity> findAllByBar(String bar, Pageable pageable);
        Long countAllByBar(String bar);
    }
    

    然后像这样组合这两个查询:

    List<FooEntity> fooList = repository.findAllByBar("...", pageable);
    Long fooTotalCount = repository.countAllByBar("...");
    
    Page<FooEntity> fooPage = PageableExecutionUtils.getPage(fooList, pageable, () -> fooTotalCount);
    

    “您的解决方法中的错误是您的自定义查询。在 Spring Data JDBC 2.0 中,您不需要使用它,除了特殊查询但它们不支持可分页。”

    可以找到可能的参数:

    https://docs.spring.io/spring-data/jdbc/docs/current/reference/html/#jdbc.query-methods

    感谢德克,

    我还找到了一种解决方法,可以通过自定义查询运行它。只需使用 limit、offset 和 orderBy 作为附加参数,如下所示:

        @Query("select * from person where firstname = :name order by :order limit :size offset :offset")
        List<Customer> findByFirstNameCustomQuery(@Param("name") String name, Pageable page, @Param("offset") long offset,
                @Param("size") long size, @Param("order") String order);
    

    然后更改服务内部的调用,例如:

    List<Customer> custList = customerRepository.findByFirstNameCustomQuery(firstname, pageable, ....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-12
      • 2015-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      • 2016-08-29
      • 2015-12-07
      相关资源
      最近更新 更多