Search This Blog

Tuesday, 4 September 2012

HQL and aliases

In the previous post we saw how query execution works in Hibernate and we created a simple relationship that we could use to test our different HQL queries.
Continuing from the last example "from Entity", I decided to try out aliases.
final Session session = sessionFactory.openSession();
Query q = session.createQuery("from Master as master");
List<Master> masters = q.list();
The logs indicate the SQL query as below:
3531 [main] DEBUG org.hibernate.SQL  - 
    Master as master */ 
        master0_.ID as ID1_,
        master0_.DATA as DATA1_ 
        ENTITY_MASTER master0_
As can be seen the generated query is more or less same as a select query without the alias. I had expected that the generated SQL would use my supplied alias. But that is not the case. From the hibernate docs:
In order to refer to the Cat in other parts of the query, 
you will need to assign an alias. For example:
from Cat as cat
This query assigns the alias cat to Cat instances, so you can use 
that alias later in the query. The as keyword is optional. You 
could also write:
from Cat cat
Multiple classes can appear, resulting in a cartesian product or "cross" join.
from Formula, Parameter
from Formula as form, Parameter as param
It is good practice to name query aliases using an initial lowercase 
as this is consistent with Java naming standards for local variables 
(e.g. domesticCat).
Thus the alias we use is only for use in our HQL and does not reflect in the SQL query generated.

No comments:

Post a Comment