"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Return Custom Objects from Spring Data JPA GROUP BY Queries?

How to Return Custom Objects from Spring Data JPA GROUP BY Queries?

Published on 2024-12-22
Browse:584

How to Return Custom Objects from Spring Data JPA GROUP BY Queries?

Custom Object Return in Spring Data JPA GROUP BY Queries

Introduction


Retrieving data as custom objects from Spring Data JPA GROUP BY queries enhances data presentation and simplifies further processing. This guide explores how to achieve this, showcasing solutions for both JPQL and native queries.

JPQL Queries


JPQL queries within the JPA specification offer native support for returning custom objects.

Step 1: Create a Custom Bean


Define a simple bean class to represent the desired output structure:

public class SurveyAnswerStatistics {
  private String answer;
  private Long cnt;

  // Constructor
}

Step 2: Return Bean Instances


Update the repository method to return instances of the custom bean:

public interface SurveyRepository extends CrudRepository {
    @Query("SELECT new com.path.to.SurveyAnswerStatistics(v.answer, COUNT(v)) FROM Survey v GROUP BY v.answer")
    List findSurveyCount();
}

Native Queries


While native queries lack direct support for the new keyword, Spring Data Projection interfaces provide an alternative solution:

Step 1: Define a Projection Interface


Create a projection interface with properties corresponding to the desired output:

public interface SurveyAnswerStatistics {
  String getAnswer();
  int getCnt();
}

Step 2: Return Projected Properties


Update the repository method to return projected properties:

public interface SurveyRepository extends CrudRepository {
    @Query(nativeQuery = true, value =
            "SELECT v.answer AS answer, COUNT(v) AS cnt FROM Survey v GROUP BY v.answer")
    List findSurveyCount();
}

Employ the SQL AS keyword to map result fields to projection properties seamlessly.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3