I get a CriteriaBuilder from the EntityManager and create a CriteriaQuery that returns Book entities.

Then I define the FROM clause by setting the Book entity as the Root of the query.

In the next step, I call the asc method on the CriteriaBuilder to create an ascending Order of the title attribute. The Book_ class, which I use to reference the title attribute, is part of the JPA metamodel. I then use the Order object to create the ORDER BY clause.

That’s all you need to do to define a CriteriaQuery with an ORDER BY clause. You can then use the CriteriaQuery to create and execute a TypedQuery.

Based on the CriteriaQuery, Hibernate generates the following SQL statement.

07:12:02,889 DEBUG [org.hibernate.SQL] -
select
book0_.id as id1_1_,
book0_.publisherid as publishe5_1_,
book0_.publishingDate as publishi2_1_,
book0_.title as title3_1_,
book0_.version as version4_1_
from
Book book0_
order by
book0_.title asc

Get this Hibernate Tip as a printable PDF!

Join the free Thoughts on Java Library to get access to lots of member-only content, like a printable PDF for this post, lots of cheat sheets and 2 ebooks about Hibernate.