Sorting in Hibernate using HQL

In this post, we will see Sorting in hibernate using HQL and Spring Boot.

Sorting in Hibernate using HQL

Let’s see what we are going to do here. We will have an entity(Student) which contains four fields(id, name, rollNumber and university). First, we will save some entity and then we will perform sorting while fetching the entities from database using HQL.

 

 

First, we will create entityManager object and then we will get Session Object from entityManger object using unwrap() method.

@PersistenceContext
EntityManager entityManager;

 

Session session = entityManager.unwrap(Session.class);

Prepare HQL.

String hql = "FROM Student s ORDER BY s.name asc";

Create Query reference using createQuery() method of Session.

Query query = session.createQuery(hql);

Get the list of the entity using getResultList() method of Query.

List<Student> studentResponse = query.getResultList();

 

Let’s see the complete code as below.

 

HQL Query to sort on basis of multiple fields.

String hql = "FROM Student s ORDER BY s.name asc, s.rollNumber desc";

Hibernate: select student0_.id as id1_0_, student0_.name as name2_0_, student0_.roll_number as roll_number3_0_, student0_.university as university4_0_ from student student0_ order by student0_.name asc, student0_.roll_number desc

 

 

Let’s see an example of Sorting in hibernate using HQL, Spring Boot and Oracle.

Open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’ click on next.  Fill all details(GroupId – sortinghql, ArtifactId – sortinghql and name – sortinghql) and click on finish. Keep packaging as the jar.

Modify pom.xml

Note – In pom.xml we have defined javac.exe path in configuration tag. You need to change accordingly i.e where you have installed JDK.

If you see any error for oracle dependency then follow these steps.

Directory structure –

Sorting in Hibernate using HQL

 

 

Student.java

StudentController.java

StudentRepository.java – interface

StudentService.java – interface

 

StudentServiceImpl.java

SpringMain.java

 

JpaConfig.java

application.properties

Let’s run the SpringMain class(run as java application).

Perform save operation first using below REST API.

http://localhost:9091/student/saveall

Request Data –

Response Data –

 

 

Sorting in Hibernate using HQL

 

http://localhost:9091/student/getall – Observe the below response data. it’s in sorting order.

 

Generated Query –

Hibernate: select student0_.id as id1_0_, student0_.name as name2_0_, student0_.roll_number as roll_number3_0_, student0_.university as university4_0_ from student student0_ order by student0_.name asc

 

That’s all about Sorting in hibernate using HQL and Spring Boot.

You may like.

 

HQL Docs.

Top