@OrderBy is a JPA annotation used to define the sorting of elements in a collection within an entity. It ensures that related data is retrieved in a specific order (ascending or descending) directly from the database.
- Applies sorting on collection relationships like @OneToMany
- Supports ordering using entity fields (ASC/DESC)
- Improves data readability by returning ordered results
Examples of @OrderBy Annotation in JPA
Below examples demonstrate how @OrderBy is used to sort associated entities within collection properties.
@Entity
public class Department {
// on the below line we are creating a variable for department id.
@Id
@GeneratedValue
private Long departmentID;
// on the below line we are creating a string variable for department name.
private String departmentName;
// on the below line we are creating a variable for
// employees list and ordering it by the employeeName field in ascending order.
@OneToMany(mappedBy = "department")
@OrderBy("employeeName ASC")
private List<Employee> employees;
}
// on the below line we are creating an Employee class.
@Entity
public class Employee {
// on the below line we are creating an employee id variable.
@Id
@GeneratedValue
private Long empID;
// on the below line we are creating an employee name variable.
private String employeeName;
@ManyToOne
@JoinColumn(name = "departmentID")
private Department department;
}
Explanation: This defines a Department entity where the employees collection is retrieved in ascending order based on the employeeName field using @OrderBy("employeeName ASC").
@Entity
public class Team {
// on the below line we are creating a variable for team
@Id
@GeneratedValue
private Long id;
// on the below line we are creating a string variable for team name.
private String teamName;
// players list and ordering it by the playerName field in ascending order.
@OneToMany(mappedBy = "team")
@OrderBy("playerName ASC")
private List<Player> players;
}
// on the below line we are creating a Player class.
@Entity
public class Player {
// on the below line we are creating a player id variable.
@Id
@GeneratedValue
private Long playerID;
// on the below line we are creating an player name variable.
private String playerName;
// joining it with column using id.
@ManyToOne @JoinColumn(name = "id") private Team team;
}
Explanation: This defines a Team entity where the players collection is retrieved in ascending order based on the playerName field using @OrderBy("playerName ASC").