Wednesday, June 29, 2005

Selecting specific objects on a Hibernate Query Join

I ran into a problem when I was trying to select specific columns from multiple tables in a join. I was having trouble casting the returned fields into an object type.

I thought that I would share the two different solutions that I came up with when I found in the Hibernate documentation.

Let me know if you have questions...since I just found this, I may or may not be able to answer it, but I'll try.

Queries may return multiple objects and/or properties as an array of type Object[]

select mother, offspr, mate
from eg.DomesticCat as mother
inner join mother.mate as mate
left outer join mother.kittens as offspr


When this is done, you have to iterate over the Object array and cast it back into the object type that each one is and call the constructor of
the item you are using.

for (Iterator lIterator=lFamilyList.iterator();
lIterator.hasNext();)
{
Object[] lObjectArray = (Object[]) lIterator.next();
Family lFamily = new Family((String) lObjectArray [0],
(String) lObjectArray [1],
(String) lObjectArray [2]);
System.out.println("Mother: " + lFamily.getMother());
System.out.println("Mate: " + lFamily.getMate());
System.out.println("Offspr: " + lFamily.getOffspr());
}

or as an actual typesafe Java object

select new Family(mother, mate, offspr)
from eg.DomesticCat as mother
join mother.mate as mate
left join mother.kittens as offspr


When this is done, you just have to cast it back to it's appropriate class when you iterate.

   for (Iterator lIterator = lFamilyList.iterator();
lIterator.hasNext();)
{
Family lFamily = (Family) lIterator.next();
System.out.println("Mother: " + lFamily.getMother());
System.out.println("Mate: " + lFamily.getMate());
System.out.println("Offspr: " + lFamily.getOffspr());
}

assuming that the class Family has an appropriate constructor.

1 comment:

Anonymous said...

This is very important for hibernate more tables join.