Spring数据分页

面对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不会执行其他一些查询来获取类别。

lzr5210 回答:Spring数据分页

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

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

    // your custom repo methods...
}
,

尝试一下

@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);
,

为了计算正确的页面信息,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,                                  可分页可分页);

本文链接:https://www.f2er.com/3142111.html

大家都在问