Sunday, May 17, 2015

How to get aggregated (grouped) entities in Spring Data JPA

For example, if you want to get aggregated entities (`PerformanceTestResult`s),

you need a new entity type (`AggregatedPerformanceTestResult`)

and you can do the following:

public interface PerformanceTestResultRepository extends JpaRepository<PerformanceTestResult, Long> {

  @Query("select new AggregatedPerformanceTestResult("
      + "min(p.id), p.testCaseId, sum(p.activeWorkerCount), p.timestamp, min(p.collectedTime), "
      + "sum(p.requestCount), sum(p.timeoutCount), sum(p.totalResponseTime)) "
      + "from PerformanceTestResult p "
      + "where p.testCaseId = :testCaseId group by p.timestamp order by p.timestamp asc")
  List<AggregatedPerformanceTestResult> getAggregatedTestResultsByTestCaseId
      (@Param("testCaseId") long testCaseId);

}

Any better way?

Reference:
https://weblogs.java.net/blog/2007/04/25/java-persistence-query-return-types

No comments:

Post a Comment