Java Reference
In-Depth Information
CHAPTER 9
n n n
Searches and Queries
I n the last chapter, we discussed how the Hibernate session is used to interact with the data-
base. Some of the session's methods take query strings in their parameter lists or return Query
objects. These methods are used to request arbitrary information from the database. In order to
fully show how they're used, we must introduce you to the HQL used to phrase these requests.
As well as extracting information (with SELECT ), HQL can be used to alter the information in the
database (with INSERT , UPDATE , and DELETE ). We cover all of this basic functionality in this chap-
ter. Hibernate's query facilities do not allow you to alter the database structure.
HQL is an object-oriented query language, similar to SQL, but instead of operating on
tables and columns, HQL works with persistent objects and their properties.
HQL is a language with its own syntax and grammar. HQL is written as strings, like from
Product p , as opposed to Hibernate's criteria queries (discussed in the next chapter), which
take the form of a conventional Java API. Ultimately, your HQL queries are translated by
Hibernate into conventional SQL queries, and Hibernate also provides an API that allows
you to directly issue SQL queries.
HQL
While most ORM tools and object databases offer an object query language, Hibernate's HQL
stands out as being complete and easy to use. Although you can use SQL statements directly
with Hibernate (which is covered in detail in the “Using Native SQL” section of this chapter),
we recommend that you use HQL (or criteria) whenever possible to avoid database portability
hassles, and to take advantage of Hibernate's SQL-generation and caching strategies. In addi-
tion to its technical advantages over traditional SQL, HQL is a more compact query language
than SQL because it can make use of the relationship information defined in the Hibernate
mappings.
We realize that not every developer trusts Hibernate's generated SQL to be perfectly opti-
mized. If you do encounter a performance bottleneck in your queries, we recommend that you
use SQL tracing on your database during performance testing of your critical components. If
you see an area that needs optimization, we suggest trying first to optimize using HQL, and
only later dropping into native SQL. Hibernate 3 provides statistics information through a JMX
MBean, which you can use for analyzing Hibernate's performance. Hibernate's statistics also
give you insight into how caching is performing.
193
Search WWH ::




Custom Search