JPA GROUP BY clause

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Continuing with JPQL clauses, we will look into JPA GROUP BY clause in this article. JPA Group By clause defines the grouping expressions over which the results will be aggregated. A grouping expression is single valued path expression variable or an identification variable.

JPA GROUP BY Clause:

Let us continue with the domain model that we have used in previous examples, database diagramOuter join

Data in Teacher table is as follows:

3 Prasad Kharkar 20000 6
4 Sushsant Pangarkar 40000 6
5 Pranil Gilda 20000 8

 

Data in Department table is as follows:

4 Mathematics
6 Science
8 Language

 

Now consider we want to count the number of teacher for each department. We can use JPA GROUP BY clause for the same. The query would be as follows.

We can execute this using

This will print results as follows.

Here, JPA GROUP BY clause have grouped the results from the query according to the name of department.

  • SELECT d.name, COUNT(t) FROM Department dSelects the name of department and total count of teachers.
  • JOIN d.teachers t Joins Department entity to Teacher entity
  • GROUP BY d.name This JPA GROUP BY clause groups the results according to name of department. If this clause wasn’t present, then the results would have been grouped as one and not be the department.

I hope this exampled helped understand JPA GROUP BY clause.

 

References for further study :

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

3 thoughts on “JPA GROUP BY clause

Leave a Reply

Your email address will not be published. Required fields are marked *