The queries we’ve been using so far have returned entire persistent objects. This is the most common use of an
object/relational mapping service like Hibernate, so it should come as no
surprise. Once you’ve got the objects, you can use them in whatever way
you need to within the familiar realm of Java code. There are
circumstances where you might want only a subset of the properties that
make up an object, though, such as producing reports.
HQL can accommodate such needs, in exactly the same way
you’d use ordinary SQL—projection in a
Suppose we want to change QueryTest.java to display only the titles of
the tracks that meet our search criteria, and we want to extract only
that information from the database in the first place. We’d start by
changing the query of Example 3-11 to retrieve only the
property. Edit Track.hbm.xml to
make the query look like Example 9-6.
Example 9-6. Obtaining just the titles of the short tracks
<query name="com.oreilly.hh.tracksNoLongerThan"> <![CDATA[
select track.titlefrom com.oreilly.hh.Track as track where track.playTime <= :length ]]> </query>
Make sure the
method in QueryTest.java is set up
to use this query. (If you edited it to use criteria queries in Chapter 8, change it back
to the way it was in Example 3-12. To save you the trouble of hunting that
down, it’s reproduced in Example 9-7.)
Example 9-7. HQL-driven query method, using the query mapped in Example 9-6 ...