使用Spring Data JPA 執行複雜查詢時,有必要傳回自訂對象,而不是傳回自訂對象,而不是傳回自訂對象定義物件預設實體。其中一個場景涉及按特定欄位對結果進行分組並檢索每組的計數。本文將探討實現此目的的兩種方法:一種用於 JPQL 查詢,另一種用於本機查詢。
JPQL 提供使用 new 關鍵字傳回自訂物件的本機支援。其實作方式如下:
<code class="java">public interface SurveyRepository extends CrudRepository<Survey, Long> { @Query("SELECT new com.path.to.SurveyAnswerStatistics(v.answer, COUNT(v)) FROM Survey v GROUP BY v.answer") List<SurveyAnswerStatistics> findSurveyCount(); } public class SurveyAnswerStatistics { private String answer; private Long cnt; // getters and setters here }</code>
原生查詢不支援new關鍵字。相反,請使用 Spring Data 投影介面:
<code class="java">public interface SurveyAnswerStatistics { String getAnswer(); int getCnt(); } public interface SurveyRepository extends CrudRepository<Survey, Long> { @Query(nativeQuery = true, value = "SELECT v.answer AS answer, COUNT(v) AS cnt FROM Survey v GROUP BY v.answer") List<SurveyAnswerStatistics> findSurveyCount(); }</code>
重要提示:
以上是如何從 Spring Data JPA GROUP BY 查詢傳回自訂物件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!