Sprin JPA how to get AVG of a column

Viewed 2435

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

In spring + Jpa I can access through Repository to function "autogenerated" like findById, count etc. Is there a similar function to calculate the average of a column values?

I found that calculate the average is possible with an explicit query in SQL like

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

or directly via java, picking all the column values and calculating the average. But these method are...dirty?

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

1 Answers

Spring Data JPA doesn't support aggregate functions in queries using method names. The suggested approach is to use @Query as mentioned in your question. Why do you consider it dirty? It isn't IMHO.

Related