我的后端必须返回以下结构的数据:
data: [{
key: "Group 1",
items: [ ... ],
count: 3,
},{
key: "Group 2",
items: [ ... ],
count: 9,
} ...]
此数据必须可排序且可分页。以下代码正在执行此操作:
public Page<Report> getReports(Integer skip, Integer take, String sortParams, String group) {
Pageable pageable = createPageable(skip, take, sortParams);
Specifications<Report> filters = (Specifications<Report>) getFilters();
return this.reportRepository.findAll(filters, pageable);
}
@Repository
public interface ReportRepository extends PagingAndSortingRepository<Report, String>, JpaSpecificationExecutor<Report> {
}
此外,我想按报告类的属性对结果进行分组。有没有办法用 spring-data 来做到这一点?我在他们的 API 中找不到任何内容。
最佳答案
问题是 - 在可以使用group by的情况下,您能否通过直接查询数据库来获得您想要的结果?
根据经验,如果您可以从数据库中获取所需格式的结果,则始终可以使用 native 查询在 Spring Data 中获取结果,并将结果存储在为其编写的 POJO 中。
在下面的示例中,我假设您有一个仅用于存储结果的新对象,名为Result。由于您没有准确指定将在数据库中使用的查询结果的结构,因此我没有提供 Result 的类定义。我使用的查询只是基本的分组依据,您应该将其替换为您自己的查询。
在存储库界面中,使用 group by 创建 native 查询:
@Repository
public interface ReportRepository extends PagingAndSortingRepository<Report, String>, JpaSpecificationExecutor<Report> {
@Query(value="Select grp, count(grp) from report group by grp", nativeQuery=true)
List<Result> findAggregatedResults();
}
关于java - 如何使用 spring-data 获取分页和排序组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57251172/