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

Order results according to an order in Hibernate 

Suppose we have a class
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;

public class Category {

 public Category(){}
 public Category(Long id){
  this.id = id;
 public Category(Long id, String name){
  this.id = id;
  this.name = name;
 @Column(nullable=false, name="id")
 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
  • Order by propertyName name in descending order
  • Order by propertyName name in random order
                  criteria.add(Restrictions.sqlRestriction("1=1 order by rand()"));
    The above code will return the list of Category domain objects in a random order.

No comments :

Post a Comment