Hibernate生成交叉连接而不是左连接

时间:2013-03-10 09:22:15

标签: mysql hibernate hql left-join cross-join

我正在使用hibernate 3.6.10.Final和MySQL 5.5。

我写了一个像这样的动态查询:

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

我的hibernate实体有多对一的父/子关系。 如果查询是由父项中的字段排序的,那么hibernate会生成这个hql select:

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

如果查询是按来自child的字段排序的,我有以下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

第二个查询返回的结果较少,因为parent0_.ID_CHILD可以为null。 有没有办法强制hibernate生成左连接?

我需要这样的东西

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

1 个答案:

答案 0 :(得分:2)

感谢JB Nizet,我解决了这样的问题:

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;