In SQL, we use the ORDER BY
clause to sort a result by column name and either ascending or descending order. We can achieve the same thing in hibernate as well.
Let's suppose that we selected all the records from the employee table, and then, by default, the records were sorted by the primary key column. But now, we want all the records to be sorted by the descending order of firstName
.
Now, the scenario is to select all the employees and order them using their first name.
The equivalent SQL query to do this is is as follows:
SELECT * FROM employee ORDER BY firstName DESC;
Consider the following table data for this recipe:
department |
salary |
firstName |
id |
---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Let's take a look at how to achieve such a condition in hibernate: