Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate - join un related objects

Tags:

hibernate

hql

I have a requirement, wherein I have to join two unrelated objects using Hibernate HQL. Here is the sample POJO class

class Product{
int product_id;        
String name;
String description;
}

and

Class Item{
int item_id;
String name;
String description;
int quantity;
int product_id; //Note that there is no composed product object.
}

Now I want to perform a query like select * from Product p left outer join Item i on p.product_id = i.item_id

I want a multidimensional array as an output of this query so that I can have separate instances of Product and Item, instead of one composed in another. Is there any way to do this in Hibernate?

like image 213
CuriousMind Avatar asked Dec 26 '10 12:12

CuriousMind


1 Answers

It is uncommon to represent an association between objects by storing the id of the associated object, rather than the associated object itself. Storing the object is more expressive and type safe, and need not have a performance impact since hibernate features lazy loading proxies.

But of course you can join things not mapped as associations in the mapping file. Quoting the hibernate reference manual:

Multiple classes can appear, resulting in a cartesian product or "cross" join.

from Formula, Parameter

from Formula as form, Parameter as param

and

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

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

Or as a List:

select new list(mother, offspr, mate.name)
from DomesticCat as mother
    inner join mother.mate as mate
    left outer join mother.kittens as offspr

Or - assuming that the class Family has an appropriate constructor - as an actual typesafe Java object:

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

You can assign aliases to selected expressions using as:

select max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n
from Cat cat

This is most useful when used together with select new map:

select new map( max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n )
from Cat cat

This query returns a Map from aliases to selected values.

Combining this with a simple where clause, we get:

select product, item
from Product product, Item item
where item.product_id = product.product_id

Edit: I missed that you want an outer join. In that case I don't know a way other than mapping the association so you can do an ordinary join on it. Note that this does not necessitate a particular form of the query result, i.e. you can still do:

select product, item
from Item item
left join item.product as product
like image 58
meriton Avatar answered Nov 16 '22 04:11

meriton