Hibernate – @OrderBy Annotation with Example
Last Updated :
07 Jun, 2023
@OrderBy annotation is used in Hibernate to specify the ordering of the elements in the collection valued property of an entity class. It is used to define the order of the elements which should be displayed. We can order the data within the entity using a specific parameter in ascending or descending order.
Examples of @OrderBy Annotation
Example 1:
Java
@Entity
public class Department {
@Id
@GeneratedValue
private Long departmentID;
private String departmentName;
@OneToMany (mappedBy = "department" )
@OrderBy ( "employeeName ASC" )
private List<Employee> employees;
}
@Entity
public class Employee {
@Id
@GeneratedValue
private Long empID;
private String employeeName;
@ManyToOne
@JoinColumn (name = "departmentID" )
private Department department;
}
|
Explanation: In the above example, the Department entity has a one-to-many relationship with the Employee entity. The @OrderBy annotation is applied to the employee’s collection in the Department entity. It specifies that the associated Employee entities should be ordered by the employee name field in ascending order. When the Department entity is being loaded from the Database, then the associated employee entity will be called and ordered based on the employee names in ascending order. The @OrderBy annotation allows you to control the order of elements in the collection-valued property which provides flexibility in how elements are retrieved and displayed in the Spring application using Hibernate.
Example 2:
Java
@Entity
public class Team {
@Id
@GeneratedValue
private Long id;
private String teamName;
@OneToMany (mappedBy = "team" )
@OrderBy ( "playerName ASC" )
private List<Player> players;
}
@Entity
public class Player {
@Id
@GeneratedValue
private Long playerID;
private String playerName;
@ManyToOne
@JoinColumn (name = "id" )
private Team team;
}
|
Explanation: In the above example the Team entity has a one-to-many relationship with the Player entity. The @OrderBy annotation is applied to the player’s collection in the Team entity. It specifies that the associated player entities should be ordered by the player name field in ascending order. When the Team entity is being loaded from the Database, the associated player entity will be called and ordered based on the player names in ascending order. The @OrderBy annotation allows you to control the order of elements in the collection-valued property which provides flexibility in how elements are retrieved and displayed in the Spring application using Hibernate.
Share your thoughts in the comments
Please Login to comment...