2

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

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

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

我的休眠实体具有多对一的父/子关系。如果查询是按父字段排序的,hibernate 会生成这个 hql 选择:

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

如果查询是按子字段排序的,我有以下 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 可以为空。有没有办法强制休眠生成左连接?

我需要这样的东西

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
4

1 回答 1

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;
于 2013-03-13T08:48:11.453 回答