@OrderBy Annotation in Hibernate for Sorting

In this post, we will see How to use @OrderBy Annotation in Hibernate for Sorting purpose using Spring Boot and Oracle. We will have two REST APIs, the first one will be used to save the entity and another one to retrieve the entity. Consider we have two entity Student.java and Book.java. Both entities are in One To Many relationships.

Student.java

Book.java

Using @OrderBy Annotation we can sort the record on basis of bookName or bookId(any field defined in Book entity).

Before moving forward let’s see some basic points about @OrderBy Annotation.

@OrderBy Annotation used with Collection type of field – @OrderBy is used with only collection type of filed(Generally in case of association mapping the field annotated with @OneToMany  or @ManyToMany or @ElementCollection annotation). If we use @OrderBy annotation with String type(or primitive/wrapper type) there is no compilation error or no exception but sorting will not work.

Note – we will see sample example of @OrderBy annotation to use with @ElementCollection type fields at the end of the post.

Correct way to use @OrderBy.

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "student_id", referencedColumnName = "id")
@OrderBy("bookName")
private List<Book> bookList = new ArrayList<Book>();

Below code snippet will not work.

@Column(name = "student_name")
@OrderBy("studentName")
private String studentName;

 

By Default @OrderBy sort in ascending order – If we don’t provide in which order we want to sort it will sort in ascending order.

@OrderBy("bookName")  – This will sort on basis of bookName as ascending order(i.e @OrderBy(“bookName”) and @OrderBy("bookName ASC") both will behave same)

We can sort in descending order as below –

@OrderBy("bookName DESC")

Using @OrderBy only – If we don’t provide field name then it will sort on the basis of the primary key. In below code, Book entity will get sort on basis of primary key i.e id.

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "student_id", referencedColumnName = "id")
@OrderBy
private List<Book> bookList = new ArrayList<Book>();

Using @OrderBy annotation with @ElementCollection type of collection – Below code snippet will give result sorted phoneNumbers as ASC.

@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "student_phone_number", joinColumns = @JoinColumn(name = "student_id"))
@OrderBy
private Set<String> phoneNumbers = new HashSet<String>();

@OrderBy annotation will work the same way even if we have an embeddable type of @ElementCollection.

@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "student_book", joinColumns = @JoinColumn(name = "student_id"))
@OrderBy("bookName")
private List<Book> bookList = new ArrayList<Book>();

See complete example about @ElementCollection annotation here.

 

Let’s see what we going to do here. We will have two entity Student and Book which is in One To Many relationship. Student can have many books.

We would have save and get APIs as below.

http://localhost:9091/student/save  – POST Operation

http://localhost:9091/student/allstudents – GET Operation

Generated Query –

Hibernate: select booklist0_.student_id as student_id4_0_0_, booklist0_.id as id1_0_0_, booklist0_.id as id1_0_1_, booklist0_.book_name as book_name2_0_1_, booklist0_.number_of_page as number_of_page3_0_1_ from book booklist0_ where booklist0_.student_id=? order by booklist0_.book_name

Let’s see @OrderBy Annotation in Hibernate for Sorting Using Spring Boot from scratch.

Open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’ click on next.  Fill all details(GroupId – orderbyexample, ArtifactId – orderbyexampleand name – orderbyexample) 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 –

@OrderBy Annotation in Hibernate for Sorting Spring Boot

 

Let’s see entity for @OrderBy Annotation in Hibernate for Sorting purpose using Spring Boot and Oracle.

Student.java

Book.java

 

 

StudentController.java

StudentRepository.java – interface

StudentService.java – interface

Business logic code and implementation for @OrderBy Annotation in Hibernate for Sorting purpose using Spring Boot and Oracle.

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/save  – POST Operation

Request Data for save operation.

http://localhost:9091/student/allstudents – GET Operation

Sorted Response data -Perform retrieve operation, Book entity will get sorted in ascending order basis of bookName(As we are using @OrderBy(“bookName”)  in our example).

 

Let’s see the sample code which tells how to define @ElementCollection types field and perform sorting using @OrderBy annotation.

You can modify Student.java and Book.java as below. The rest of logic would be the same.

Student.java

Book.java

 

If you trying to fetch student record using GET API below query will generate.

Hibernate: select phonenumbe0_.student_id as student_id1_2_0_, phonenumbe0_.phone_numbers as phone_numbers2_2_0_ from student_phone_number phonenumbe0_ where phonenumbe0_.student_id=? order by phonenumbe0_.phone_numbers asc

Hibernate: select booklist0_.student_id as student_id1_1_0_, booklist0_.author as author2_1_0_, booklist0_.book_name as book_name3_1_0_, booklist0_.number_of_page as number_of_page4_1_0_ from student_book booklist0_ where booklist0_.student_id=? order by booklist0_.book_name

 

That’s all about @OrderBy Annotation in Hibernate for Sorting purpose using Spring Boot and oracle

You may like –

@OrderBy docs.

Summary – We have seen @OrderBy Annotation in Hibernate for Sorting example hibernate and Spring Boot. We have also seen @OrderBy is used with only collection type of filed(Generally in case of association mapping the field annotated with @OneToMany or @ManyToMany or @ElementCollection annotation)

 

Top