Syntax to use OrderBy in Hibernate Criteria Query
The order can be specified using addOrder on a Criteria Objectcriteria.addOrder(Order.asc("propertyName"))
criteria.addOrder(Order.desc("propertyName"))
Order results according to an order in Hibernate
Suppose we have a classCategory.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
}
- 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()
The above code will return the list of Category domain objects in a random order.
.createCriteria(Catgeory.class)
criteria.add(Restrictions.sqlRestriction("1=1 order by rand()"));
.list();
Comments
Post a Comment