”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何从 Spring Data JPA GROUP BY 查询返回自定义对象?

如何从 Spring Data JPA GROUP BY 查询返回自定义对象?

发布于2024-12-22
浏览:598

How to Return Custom Objects from Spring Data JPA GROUP BY Queries?

Spring Data JPA GROUP BY 查询中的自定义对象返回

简介


检索将数据作为来自 Spring Data JPA GROUP BY 查询的自定义对象增强了数据表示并简化了进一步处理。本指南探讨了如何实现这一目标,展示了 JPQL 和本机查询的解决方案。

JPQL 查询


JPA 规范中的 JPQL 查询提供本机查询支持返回自定义对象。

第 1 步:创建自定义 Bean


定义一个简单的 Bean表示所需输出结构的类:

public class SurveyAnswerStatistics {
  private String answer;
  private Long cnt;

  // Constructor
}

第 2 步:返回 Bean 实例


更新存储库方法以返回自定义 Bean 的实例:

public interface SurveyRepository extends CrudRepository {
    @Query("SELECT new com.path.to.SurveyAnswerStatistics(v.answer, COUNT(v)) FROM Survey v GROUP BY v.answer")
    List findSurveyCount();
}

原生查询


虽然原生查询缺乏对 new 关键字的直接支持,但 Spring Data Projection 接口提供了替代解决方案:

第 1 步:定义投影接口


创建一个投影接口,其属性与所需的属性相对应输出:

public interface SurveyAnswerStatistics {
  String getAnswer();
  int getCnt();
}

第 2 步:返回投影属性


更新存储库方法以返回投影属性:

public interface SurveyRepository extends CrudRepository {
    @Query(nativeQuery = true, value =
            "SELECT v.answer AS answer, COUNT(v) AS cnt FROM Survey v GROUP BY v.answer")
    List findSurveyCount();
}

使用 SQL AS 关键字将结果字段无缝映射到投影属性。

最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3