Skip to Main Content
Hibernate: A Developer's Notebook
book

Hibernate: A Developer's Notebook

by James Elliott
May 2004
Intermediate to advanced content levelIntermediate to advanced
192 pages
4h 46m
English
O'Reilly Media, Inc.
Content preview from Hibernate: A Developer's Notebook

9.3. Sorting

It should come as no surprise that you can use a SQL-style "order by"clause to control the order in which your output appears. I've alluded to this several times in earlier chapters, and it works just like you'd expect. You can use any property of the objects being returned to establish the sort order, and you can list multiple properties to establish sub-sorts within results for which the first property values are the same.

9.1.1. How do I do that?

Sorting is very simple: you list the values that you want to use to sort the results. As usual, where SQL uses columns, HQL uses properties. For Example 9-13, let's update the query in Example 9-10 so that it displays the results in reverse alphabetical order.

Example 9-13. Addition to Track.hbm.xml that sorts the results backwards by title
<query name="com.oreilly.hh.tracksNoLongerThan">
  <![CDATA[
      select track.id, track.title from com.oreilly.hh.Track as track
      where track.playTime <= :length
      order by track.title desc
    ]]>
</query>

As in SQL, you specify an ascending sort using "asc" and a descending sort with "desc".

The output from running this is as you'd expect (Example 9-14)

Example 9-14. Titles and IDs in reverse alphabetical order
% ant qtest Buildfile: build.xml prepare: [copy] Copying 1 file to /Users/jim/Documents/Work/OReilly/Hibernate/ Examples/ch09/classes compile: qtest: [java] Track: Video Killed the Radio Star [ID=1] [java] Track: Test Tone 1 [ID=6] [java] Track: Russian Trance [ID=0] [java] Track: Never Turn ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Getting Started with Hibernate 3

Getting Started with Hibernate 3

James Elliott

Publisher Resources

ISBN: 0596006969Supplemental ContentCatalog PageErrata