Spring Data JPA GROUP BY 查詢中的自訂物件回傳
Spring Data JPA 提供了一種使用JPQL(Java PJavaers資料庫操作的便捷方法查詢語言)。當使用 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中文網其他相關文章!