Chapter 8. Criteria Queries

Relational query languages like HQL (and SQL, on which HQL is based) are extremely flexible and powerful, but they take a long time to truly master. Many application developers get by with a rudimentary understanding, cribbing similar examples from past projects, and calling in database experts when they need to come up with something truly new, or to understand a particularly cryptic query expression.

It can also be awkward to mix a query language’s syntax with Java code. The section “Better Ways to Build Queries” in Chapter 3 showed how to at least keep the queries in a separate file so they can be seen and edited in one piece, free of Java string escape sequences and concatenation syntax. Even with that technique, though, the HQL isn’t parsed until the mapping document is loaded, which means that any syntax errors it might harbor won’t be caught until the application is running.

Hibernate offers an unusual solution to these problems in the form of criteria queries. They provide a way to create and connect simple Java objects that act as filters for picking your desired results. You can build up nested, structured expressions. The mechanism also allows you to supply example objects to show what you’re looking for, with control over which details matter and which properties to ignore.

As you’ll see, this can be quite convenient. To be fair, it has its own (very minor) disadvantages. Expanding long query expressions into a Java API makes them take up more ...

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.