Custom Object Return in Spring Data JPA GROUP BY Queries
Spring Data JPA offers a convenient way to perform database operations using JPQL (Java Persistence Query Language). When using a custom JPQL query with a GROUP BY clause, you may want to return custom objects instead of the inbuilt SQL result arrays.
JPQL Solution
<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>
Native Query Solution
For native queries, Spring Data Projection interfaces are used instead of bean classes:
<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>
Important Notes
The above is the detailed content of How to Return Custom Objects in Spring Data JPA GROUP BY Queries?. For more information, please follow other related articles on the PHP Chinese website!