Pages

Showing posts with label Criteria API. Show all posts
Showing posts with label Criteria API. Show all posts

Thursday, April 26, 2012

Use Hibernate Criteria API to Order By based on Association

Problem Statement: I am working with Hibernate to read database table. Not able to apply order by on associated object's attributes.

Problem Solution: Solution is to use criteria alias.

Sort by Cat.name.

List cats = sess.createCriteria(Cat.class)
    .addOrder( Order.asc("name") )
    .list();
In the statement below associated objects's name property is used for sorting. In this case sort will be on Cat.kittens.name
List cats = sess.createCriteria(Cat.class)
    .createAlias("kittens", "kt")
    .addOrder( Order.asc("kt.name") )
    .list();

Read more