1

在我的项目中,我有一个扩展 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

希望得到一些帮助...

4

1 回答 1

1

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

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, ....
于 2020-08-03T19:48:17.230 回答