When performing complex queries using Spring Data JPA, it becomes necessary to return custom objects rather than the default entities. One such scenario involves grouping the results by a specific field and retrieving the count for each group. This article will explore two methods for achieving this: one for JPQL queries and one for native queries.
JPQL provides native support for returning custom objects using the new keyword. Here's how it's done:
<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>
Native queries do not support the new keyword. Instead, use Spring Data projection interfaces:
<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>
Important Notes:
The above is the detailed content of How to Return a Custom Object from a Spring Data JPA GROUP BY Query?. For more information, please follow other related articles on the PHP Chinese website!