JPA order 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)

Hello, Previously we have seen about JPA CASE expressions. This article deals with JPA ORDER BY clause.

JPA ORDER BY clause:

Sometime we may need to sort the entities in ascending or descending order of some field. JPA ORDER BY clause lets us achieve this. You can sort the entities returned by entity manager according to ascending of descending order of entity fields.

JPA ORDER BY clause example:

Taking the same object model from previous examples, our Teacher entity is as follows.

2014-04-20 10_18_52-MySQL Workbench

We want to retrieve Teacher entities in sorted order according to their salaries. The query for the same would be

We can execute this using

This will give output,

Prasad 20000
Pranil 20000
Sushsant 40000

If you want to sort the entities using descending order, then the jpa order by clause changes to

It gives results as follows

Sushsant 40000
Prasad 20000
Pranil 20000

I hope this example helped understand jpa order by clause.

Please feel free to suggest improvements.

 

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.

Leave a Reply

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