java - 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;
我的问题是是否有更简单的方法来做到这一点,或者我仍然需要自定义查询(我是否需要在实体中移动自定义查询或使用命名查询来代替?)?
解决方案
当您想要聚合结果时,通常使用 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);
推荐阅读
- javascript - Excel VBA 登录网站并获取一些文件
- javascript - 如何在 A-Frame 中使用 Chart.js?
- python - 如何使用 Python 捕获“FedAuth”-cookie 以连接到 SharePoint?
- raku - 如何将 CArray[of-struct] 从 Raku 传递给 C?
- vue.js - 更改 Vue 中的分隔符?
- svelte - 让 Svelte 在 shadow dom 中添加样式
- python - 尝试使用 python 列表填充矩阵
- javascript - 无法使用 three.js 和 ObjLoader2 加载 obj 文件
- c# - EF Core 无法执行数据库更新命令:“失败:Microsoft.EntityFrameworkCore.Database.Command[20102]”
- python - 连接方法调用结果