@OrderBy annotation in detail
@OrderBy is used to sort the records either in ascending order or descending order. Also, please note that @OrderBy works only with the data member of an entity class which are collection type. It doesn’t work with plain string data members. Even if you mark a String field with this annotation, no error will happen, but it won’t sort the elements also. Let’s take one example in which we will establish a mapping between Teacher class and the Subject class that he/she teaches.
package com.sks;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
@Entity
@Table(name="Teacher")
public class Teacher {
@Id
private int id;
private String name;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "teacher_id", referencedColumnName = "id")
@OrderBy("subjectName")
private List<Subject> subjects;
//getters and setters
}
-> Note – Default sorting order is ascending. For sorting in descending order, mention desc e.g. @OrderBy(“subjectName desc”)
package com.sks;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "Subject")
public class Subject {
@Id
private int id;
private String subjectName;
//getters and setters
}
Using @OrderBy without parameter: If we don’t mention the field name on which ordering should happen, then ordering happens on primary key. For e.g. in the below example, the ordering of subjects will happen on ‘id’ of Subject class which is primary key in the table.
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "teacher_id", referencedColumnName = "id")
@OrderBy
private List<Subject> subjects;