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.3.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.
As in SQL, you specify an ascending sort using "asc" and a descending sort with "desc".
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>
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 Your Back on Mother Earth [ID=11] [java] Track: Motherless Child [ID=12] [java] Track: In a Manner of Speaking [ID=8] [java] Track: Gone [ID=10]