Java Reference
In-Depth Information
Logging the Underlying SQL
Hibernate can output the underlying SQL behind your HQL queries into your application's log
file. This is especially useful if the HQL query does not give the results you expect, or the query
takes longer than you wanted. You can run the SQL that Hibernate generates directly against
your database in the database's query analyzer at a later date to determine the causes of the
problem. This is not a feature you will have to use frequently, but it is useful should you need
to turn to your database administrators for help in tuning your Hibernate application.
The easiest way to see the SQL for a Hibernate HQL query is to enable SQL output in
the logs with the hibernate.show_sql property. Set this property to true in your hibernate.
properties or hibernate.cfg.xml configuration files, and Hibernate will output the SQL
into the logs. You do not need to enable any other logging settings—although setting log-
ging for Hibernate to debug also outputs the generated SQL statements, along with a lot of
other verbiage.
After enabling SQL output in Hibernate, you should rerun the previous example. Here is
the generated SQL statement for the HQL statement from Product :
select product0_.id as id, product0_.name as name0_, product0_.description å
as descript3_0_, product0_.price as price0_, product0_.supplierId å
as supplierId0_, product0_1_.version as version1_, å
case when product0_1_.productId is not null then 1 å
when product0_.id is not null then 0 end å
as clazz_ from Product product0_ left outer join Software product0_1_ å
on product0_.id=product0_1_.productId
As an aside, remember that the Software class inherits from Product , which complicates
Hibernate's generated SQL for this simple query. When we select all objects from our simple
Supplier class, the generated SQL for the HQL query from Supplier is much simpler:
select supplier0_.id as id, supplier0_.name as name2_ from Supplier supplier0_
When you look in your application's output for the Hibernate SQL statements, they will
be prefixed with Hibernate: . The previous SQL statement would look like this:
Hibernate: select supplier0_.id as id, supplier0_.name as name2_ å
from Supplier supplier0_
If you turn your log4j logging up to debug for the Hibernate classes, you will see SQL state-
ments in your log files, along with lots of information about how Hibernate parsed your HQL
query and translated it into SQL.
Commenting the Generated SQL
Tracing your HQL statements through to the generated SQL can be difficult, so Hibernate pro-
vides a commenting facility on the Query object that lets you apply a comment to a specific
query. The Query interface has a setComment() method that takes a String object as an argu-
ment, as follows:
public Query setComment(String comment)
Search WWH ::




Custom Search