Chapter 9. A Look at HQL

We have already used HQL queries a few times in previous chapters. It’s worth spending a little time looking at how HQL differs from SQL and some of the useful things you can do with it. As with the rest of this book, our intention is to provide a useful introduction and some examples, not a comprehensive reference.

As we mentioned back in Chapter 7, JPA’s query language is a subset of HQL. So if you learn HQL, you’ll be able to read JPA query language (QL) quite well, although if you’re trying to write queries in the JPA you may well be tempted to go beyond its capabilities. That’s a small price to pay for being able to use Hibernate most of the time.

Tip

As noted at the end of Chapter 7, the examples in this chapter rely on the use of XML mapping files, so if you changed things around to work with annotations, you’ll probably want to download the code examples to start over in this chapter’s folder.

Writing HQL Queries

We’ve already shown that you can get by with fewer pieces in an HQL query than you might be used to in SQL (the queries we’ve been using, such as those in Chapter 3, have generally omitted the select clause). In fact, the only thing you really need to specify is the class in which you’re interested. Example 9-1 shows a minimal query that’s a perfectly valid way to get a list of all Track instances persisted in the database.

Note

HQL stands for Hibernate Query Language. And SQL? It depends who you ask.

Example 9-1. The simplest HQL query
from Track ...

Get Harnessing Hibernate now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.