Spring Data JPA GROUP BY 查询中的自定义对象返回
Spring Data JPA 提供了一种使用 JPQL(Java Persistence)执行数据库操作的便捷方法查询语言)。当使用带有 GROUP BY 子句的自定义 JPQL 查询时,您可能希望返回自定义对象而不是内置 SQL 结果数组。
JPQL 解决方案
<code class="java">public class SurveyAnswerStatistics { private String answer; private Long count; ... // getters and setters }</code>
<code class="java">@Query("SELECT new com.path.to.SurveyAnswerStatistics(v.answer, COUNT(v)) FROM Survey v GROUP BY v.answer") public List<SurveyAnswerStatistics> findSurveyCount();</code>
原生查询解决方案
对于本机查询,使用 Spring Data Projection 接口而不是 bean 类:
<code class="java">public interface SurveyAnswerStatistics { String getAnswer(); int getCnt(); ... // additional getters }</code>
<code class="java">@Query(nativeQuery = true, value = "SELECT v.answer AS answer, COUNT(v) AS cnt FROM Survey v GROUP BY v.answer") public List<SurveyAnswerStatistics> findSurveyCount();</code>
重要说明
以上是如何在 Spring Data JPA GROUP BY 查询中返回自定义对象?的详细内容。更多信息请关注PHP中文网其他相关文章!