Skip to main content

Hibernate : fetch results using Orderby in Criteria Query

Syntax to use OrderBy in Hibernate Criteria Query

The order can be specified using addOrder on a Criteria Object
criteria.addOrder(Order.asc("propertyName"))
criteria.addOrder(Order.desc("propertyName"))

Order results according to an order in Hibernate 

Suppose we have a class
Category.java
package com.ekiras.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="category")
public class Category {

public Category(){}
public Category(Long id){
this.id = id;
}
public Category(Long id, String name){
this.id = id;
this.name = name;
}

@Id
@Column(nullable=false, name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

@Column(nullable=false, name="name")
private String name;

// Getters and Setters

}
So if we need to order the results of this class according to a given order we can do it like following

  • Order by propertyName id in ascending order
    sessionFactory.getCurrentSession()
    .createCriteria(Catgeory.class)
    .addOrder(Order.asc("id"))
    .list();
  • Order by propertyName name in descending order
    sessionFactory.getCurrentSession()
    .createCriteria(Catgeory.class)
    .addOrder(Order.desc("name"))
    .list();
  • Order by propertyName name in random order
    sessionFactory.getCurrentSession()
    .createCriteria(Catgeory.class)
    criteria.add(Restrictions.sqlRestriction("1=1 order by rand()"));
    .list();
    The above code will return the list of Category domain objects in a random order.


Comments