Hibernate : sorting with criteria query

Sorting is very easy with criteria in hibernate.
We just need to mention the object property on which we need to set the ordering. Let’s say in the below example i to sort my order on feild “organization” of my “PtcAdoptionConsultant.class” object. If it is descensing then Order.desc can be applied.

@Transactional
public List findAllPtcConsultants() {
List ptcUsers = getSession().createCriteria(PtcAdoptionConsultant.class)
.addOrder(Order.asc(“organization”))
.list();
return  ptcUsers;
}

In case the field i want to sort on is a foreign key then how can i sort on the other table field ?
We just need to create the alias of the foreign key’s table field and by using the dot operator then can be defined for sorting.

@Transactional
public List findAllPtcConsultants() {
List ptcUsers = getSession().createCriteria(PtcAdoptionConsultant.class)
.createAlias(“ptcUser”, “user”)
.addOrder(Order.asc(“user.lastName”))
.list();
return  ptcUsers;
}

One thought on “Hibernate : sorting with criteria query

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s