As we know there are three types of joins - Left, Right and Inner Joins. These joins can be written in HQL in a shorter and convenient way.
Say there are two tables, EMPLOYEE and ADDRESS created by Hibernate.
ID | NAME |
---|---|
1 | Joe |
2 | Peter |
ID | ADDRESS_ID | STREET_NAME | CITY | PIN_CODE |
---|---|---|---|---|
1 | 1 | Walls street | Delhi | 110012 |
1 | 2 | Murugeshpalya | Bangalore | 560019 |
2 | 3 | Trisar | Hydrabad | 500003 |
2 | 4 | Dumdum | Kolkata | 700028 |
So, from the above table we can see that 'ID' is the primary key for the 'EMPLOYEE' table and the same 'ID' is the foreign key for the 'ADDRESS' table.
Now, if you are asked to get the Names of the Employees who are from 'Bangalore', your SQL query would be:
The HQL query for the same would be :
Let us see the detail explanation below:
Assuming that we have an Employee class
And an 'Address' class
And with the mapping files Employee.hbm.xml and Address.hbm.xml right in place, the main() class would be :
Instead of writing a long join query we have written a short statement in WHERE clause
which says the 'employee' object has an 'addressSet'('addressSet' contains the Set of 'Address' objects) and it should search for 'city' as 'Bangalore' in that 'addressSet'.
Finally, Hibernate takes care of converting it to the actual SQL query.