HQL (Hibernate Query Language)

Database applications, no matter how object-oriented, need to have direct access to the underlying database from time to time. We’ve already seen some reasons why (filtering data by parameterized query). The need for queries breaks down into the following categories:

  • Retrieve a collection of objects from the database all at once

  • Retrieve a sorted collection of objects from the database all at once

  • Retrieve nonobject values from the database

  • Retrieve summary information from the database

All four of these categories involve either collecting persistent objects or avoiding them altogether, making the direct object/relational mapping strategy an obstacle.

Hibernate provides Hibernate Query Language (HQL) and the Query interface to allow you to execute statements that meet these goals. Hibernate Query Language looks an awful lot like SQL. HQL queries can have a SELECT clause, a FROM clause, and a WHERE clause. You can, if you choose, author direct SQL statements as HQL queries; as long as the database can perform the query, the query will execute. On the other hand, you can use object-oriented notation instead of data-oriented notation in your HQL queries. This means, instead of using table and field names, you can use class and property names, or any mix of the two.

FROM

The FROM clause of an HQL query tells Hibernate where to look for the requested values. You can use either the name of one or more persistent classes, the name of one or more tables in the database, ...

Get Java Enterprise in a Nutshell, Third Edition 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.