Domanda

I'm using hibernate 3.6.10.Final and MySQL 5.5.

I wrote a dynamic query like this:

"from " + clazz.getName()+ " ORDER BY "+sortField+" "+sortDirection

My hibernate entities have a many to one parent/child relationship. if the query is ordered by a field from parent, hibernate generates this hql select:

select parent0_.ID as ID10_, parent0_.ID_CHILD as ID6_10_ 
from parent parent0_
order by parent0_.PARENTFIELD ASC

if the query is ordered by a field from child, i have the following hql:

select parent0_.ID as ID10_, parent0_.ID_CHILD as ID6_10_
from parent parent0_
cross join child1_
where parent0_.ID_CHILD = child1_.ID
order by child1_.CHILDFIELD ASC

The second query returns less results because parent0_.ID_CHILD can be null. Is there a way to force hibernate to generate a left join?

I need something like this

select parent0_.ID as ID10_,
   parent0_.ID_CHILD as ID6_10_
from
parent parent0_
    left join
child child1_
on
parent0_.ID_CHILD = child1_.ID
order by child1_.CHILDFIELD ASC
È stato utile?

Soluzione

Thanks to JB Nizet i solved writing the query like this:

String[] tokens = sortField.split("\\.");
for(int i=0;i<tokens.length-1;i++)
{
    sortby+=" LEFT JOIN parent"+i+"."+tokens[i]+" as child"+i;
}
sortby+=" ORDER BY child"+(tokens.length-2)+"."+tokens[tokens.length-1]+" "+sortDirection;
...
String query = "select parent0 FROM " + clazz.getName()+" as parent0 "+ sortby;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top