Thursday, September 10, 2009

Use of right join in Hibernate

Consider the following scenario where Company table has a foreign key pointing to CompanyType table and ContactPerson has a foreign key pointing to Company table.

ContactPerson –> Company –> CompanyType

In this case I want to get list of all companies with their company type name (rather than id) and name of employee. It doesn’t matter if there is any contact person available for the company or not. I at least should get the company details.

Now if you write an sql statement using left join, we would definitely get list of all companies. However with Hibernate, writing the hql statement using left join might not yield you the desired results and hence you need to use the right join as in the following example.

select
company.id as ID,
companytype.type as TYPE,
company.name as COMPNAME,
company.url as URL,
company.address as ADDRESS,
company.phone as PHONE,
contactperson.name as CONTACTPERSONNAME
from
hs.pojo.db.Companytype as companytype,
hs.pojo.db.contactperson as contactperson
right outer join
contactperson.comp as company
where
companytype.id <16 and
companytype.id >4 and
company.closed = 0 and
companytype.id = company.companytype

No comments:

Post a Comment