Search code examples
javaspringjpaspring-data-jpa

Spring Data JPA: How to get AVG of a column?


I know that there are a lot of similar questions on the internet but none of these are what I want to ask.

In Spring Data Jpa I can use method names in the Repository to autogenerate the queries like findById, count etc. Is there a similar keyword that can be added to the method name to calculate the average of a column values?

I found that calculating the average is possible with an explicit JPQL query like:

@Query(value = "SELECT avg(price) FROM Product")
public Double avg();

or directly via Java by retrieving all the column values then calculating the average programatically. But these methods are...dirty?

What is the best way to calculate the AVG (or MIN, MAX etc) in Spring Data JPA?


Solution

  • Spring Data JPA doesn't support aggregate functions in queries using method names (see the table of supported keywords here). The suggested approach is to use @Query as mentioned in your question. Why do you consider it dirty? It isn't IMHO.