Spring Data JPA provides mechanisms to execute JPQL queries and retrieve results as custom objects.
Step 1: Define a Bean Class
Create a simple bean class to represent the desired object structure:
<code class="java">public class SurveyAnswerStatistics { private String answer; private Long count; // Constructor for object instantiation }</code>
Step 2: Use the Bean in the Repository Method
Modify the repository method to return instances of the bean class:
<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(); }</code>
If using native queries, JPA-specific syntax is not supported. Instead, use:
Step 1: Create a Projection Interface
Define a projection interface to specify the properties of the desired object:
<code class="java">public interface SurveyAnswerStatistics { String getAnswer(); int getCnt(); }</code>
Step 2: Map Result Fields in the Query
Use the SQL AS keyword in the query to map result fields to projection properties:
<code class="java">@Query(nativeQuery = true, value = "SELECT v.answer AS answer, COUNT(v) AS cnt FROM Survey v GROUP BY v.answer") List<SurveyAnswerStatistics> findSurveyCount(); }</code>
The above is the detailed content of How to Retrieve Custom Objects from Spring Data JPA Grouped Query Results?. For more information, please follow other related articles on the PHP Chinese website!