首页 > 解决方案 > Spring数据JpaRepository分页和分组

问题描述

在我的 JpaRepository 界面中,我得到了以下可以正常工作的方法:

Page<PermissionRule> findByOrganizationIdAndTypeStringAndObjectReferenceIgnoreCaseContaining(
        Long organizationId, String typeId, String searchTerm, Pageable pageable);

我需要的是通过 object_reference 分组的相同查询。

这就是我尝试做的:编辑

@Query(value = "SELECT object_reference, dst_type, other FROM permission_rule pr WHERE pr.organization_id = %?1% AND pr.dst_type_id = %?2% AND pr.object_reference LIKE %?3% GROUP BY object_reference", nativeQuery = true)
Page<PermissionRule> getFunds(Long organizationId, String dstTypeId, String searchTerm, Pageable pageable);

但我收到以下错误

InvalidJpaQueryMethodException:无法在方法中使用具有动态排序和/或分页的本机查询

此外,如果它有助于我想在 GROUP BY 中使用的实体列是

@Column(name = "object_reference", nullable = false)
private String objectReference;

我的问题是是否有更简单的方法来做到这一点,或者我仍然需要自定义查询(我是否需要在实体中移动自定义查询或使用命名查询来代替?)?

标签: javahibernatespring-data-jpaspring-data

解决方案


当您想要聚合结果时,通常使用 groupBy。在这里,您正在做select *而不是聚合。

@Query("SELECT l.someCol, count(*) as numOfRows from SomeTable l GROUP BY l.someCol")
    Page<Something> findSomething(Pageable pageable);

Something对象可以是带有用于 someCol 和 numOfRows 的 getter 方法的接口。

如果您使用的是本机查询,则需要使用countQuery

@Query(value = "SELECT someCol, count(*) as numRows from SomeTable GROUP BY someCol",
            countQuery= "SELECT count(*) FROM (SELECT someCol, count(*) as numRows from SomeTable GROUP BY someCol)",
            nativeQuery=true)
    Page<Something> findSomething(Pageable pageable);

推荐阅读