Sorting the results

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.

How to do it…

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

1

50000

Yogesh

1

1

35000

Aarush

2

3

30000

Varsha

3

2

75000

Vishal

4

Let's take a look at how to achieve such a condition in hibernate:

Code

Enter the following code to sort the results according to the employee's first name:

Criteria criteria = session.createCriteria(Employee.class);   criteria.addOrder(Order.desc("firstName")); // desc() used to add order Descending
// criteria.addOrder(Order.asc("id")); // asc() used to add order Ascending

List<Employee> employees = criteria.list();
for (Employee employee : employees) {
  System.out.println(employee.toString());
}

Output

Hibernate: select this_.id as id1_1_1_, this_.department_id as departme4_1_1_, this_.firstName as firstNam2_1_1_, this_.salary as salary3_1_1_, department2_.id as id1_0_0_, department2_.deptName as deptName2_0_0_ from Employee this_ left outer join Department department2_ on this_.department_id=department2_.id order by this_.firstName desc  

Employee
 id: 1
 first name: Yogesh
 salary: 50000
 department: development

Employee
 id: 4
 first name: Vishal
 salary: 75000
 department: R&D

Employee
 id: 3
 first name: Varsha
 salary: 30000
 department: UI/UX

Employee
 id: 2
 first name: Aarush
 salary: 35000
 department: development

How it works…

In a general scenario, when the ORDER BY clause is not supplied, the database returns records in the default order in which data is stored.

Here, we applied the descending order to the firstName column, so the employee Yogesh comes first, and Aarush goes last. The order by this_.firstName desc clause is used by hibernate to get the desired results.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset