HQL: order by property of nullable property

最后都变了- 提交于 2019-12-07 04:48:31

问题


Assuming two tables, A[a_id, b_id] and B[b_id,c].

I need to execute the HQL query of form "From A a ORDER BY a.b.c", while b is nullable in class A.

The query,however, returns only instances of A which have non-null b property. This happens because Hibernate generates SQL of form "SELECT FROM A,B WHERE A.b_id = B.b_id ORDER BY B.c"

What is the way to return all instances of A with those having null in b to appear first/last?


回答1:


What about :

from A a left join a.b_fk b order by b.c

The left join takes care of making the join, even if the b_fk property on the java entity (not the table) is null.

Edited : Sorry, I mentionned sorting the nulls differently. To sort (not taking nulls into account), you can specify 'desc' to inverse the sort order (default = 'asc'). For nulls, I believe Hibernate lets the default database order... Try it yourself on your database to see what happens (sorry for misleading in first version of post).

A lot of information can be found in Hibernate's reference documentation :
http://docs.jboss.org/hibernate/stable/core/reference/en/html/queryhql.html

The rest usually depends on the database you use ...




回答2:


I have the same problem and I have resolve it like this :

SELECT a
FROM a
LEFT JOIN a.b b 
LEFT JOIN b.c c
ORDER BY c.id

It's in HQL syntax !

The "LEFT JOIN" allows to display line when the child is NULL.

In fact, if you don't specify the join, hibernate creates automatically an "INNER JOIN" which remove the NULL child.



来源:https://stackoverflow.com/questions/1272738/hql-order-by-property-of-nullable-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!