Spring数据分页

时间:2019-11-07 19:28:10

标签: java hibernate pagination spring-data-jpa

面对Spring Data JPA 2.2.0的奇怪行为。

Product和Category是具有一对多关系的两个非常简单的实体。请注意,就我而言,某些产品可能没有类别。

我进行查询

@Query("select p, c" +
        "from Product p " +
        "left join fetch Category c on p.category.id = c.id " +
        "where (:categoryId = -1L or c.id = :categoryId) and " +
        "(:priceFrom is null or p.price >= :priceFrom) and " +
        "(:priceTo is null or p.price <= :priceTo)")
Page<Product> filterProducts(@Param("categoryId") Long categoryId,
                             @Param("priceFrom") BigDecimal priceFrom,
                             @Param("priceTo") BigDecimal priceTo,
                             Pageable pageable);

但是方法调用返回Page<Object[]>而不是Page<Product>。如果我在返回类型中将Page更改为List,一切都会好的。为什么这样工作?可以更改这种行为吗?

我使用select p, c通过一个查询用产品和类别中的所有数据填充结果产品。如果没有c,则Hibernate不会执行其他一些查询来获取类别。

3 个答案:

答案 0 :(得分:0)

您的存储库接口是否扩展了JpaRepositoryPagingAndSortingRepository,例如这样(其中Long是您的实体@Id字段的类型:

@Repository
interface ProductRepository extends JpaRepository<Product, Long> {

    // your custom repo methods...
}

答案 1 :(得分:0)

尝试一下

@Query("from Product p left join fetch p.category c " +
       "where (:categoryId = -1L or c.id = :categoryId) and " +
       "(:priceFrom is null or p.price >= :priceFrom) and " +
       "(:priceTo is null or p.price <= :priceTo)")
Page<Product> filterProducts(@Param("categoryId") Long categoryId,
                                     @Param("priceFrom") BigDecimal priceFrom,
                                     @Param("priceTo") BigDecimal priceTo,
                                     Pageable pageable);

答案 2 :(得分:0)

为了计算正确的页面信息,Spring JPA还需要最大行数。 (用于计算页码)。为了实现这一点,除了原始查询定义之外,您还需要提供countQuery

@Query(value = "select p, c" +
        "from Product p " +
        "left join fetch Category c on p.category.id = c.id " +
        "where (:categoryId = -1L or c.id = :categoryId) and " +
        "(:priceFrom is null or p.price >= :priceFrom) and " +
        "(:priceTo is null or p.price <= :priceTo)",
       countQuery = "select count(p.id)" +
        "from Product p " +
        "left join fetch Category c on p.category.id = c.id " +
        "where (:categoryId = -1L or c.id = :categoryId) and " +
        "(:priceFrom is null or p.price >= :priceFrom) and " +
        "(:priceTo is null or p.price <= :priceTo)",

)     页面filterProducts(@Param(“ categoryId”)长的categoryId,                                  @Param(“ priceFrom”)BigDecimal priceFrom,                                  @Param(“ priceTo”)BigDecimal priceTo,                                  可分页可分页);