Hibernate 排序依据最后为空
Hibernate 与 PostgreSQL DB 一起使用时,按列对 desc 进行排序时,空值会高于非空值。
SQL99 标准提供关键字“NULLS LAST”来声明空值应低于非空值。
使用 Hibernate 的 Criteria API 可以实现“NULLS LAST”行为吗?
Hibernate used with PostgreSQL DB while ordering desc by a column puts null values higher than not null ones.
SQL99 standard offers keyword "NULLS LAST" to declare that null values should be put lower than not nulls.
Can "NULLS LAST" behaviour be achieved using Hibernate's Criteria API?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
鉴于 HHH-465 尚未修复,并且在不久的将来不会得到修复由于 Steve Ebersole 给出的原因,您最好的选择是全局或专门使用附加到问题的
CustomNullsFirstInterceptor
来更改 SQL 语句。我将其发布在下面供读者参考(感谢 Emilio Dolce):
Given that HHH-465 is not fixed and is not going to get fixed in a near future for the reasons given by Steve Ebersole, your best option would be to use the
CustomNullsFirstInterceptor
attached to the issue either globally or specifically to alter the SQL statement.I'm posting it below for the readers (credits to Emilio Dolce):
您可以在 hibernate 属性中配置“nullsfirst”/“nullslast”,以便默认情况下任何标准调用都会选择它:
hibernate.order_by.default_null_ordering=last
(或=first< /代码>)。
有关详细信息,请参阅此休眠提交。
You can configure "nulls first" / "nulls last" in hibernate properties so it will be picked up by any criteria call by default:
hibernate.order_by.default_null_ordering=last
(or=first
).See this hibernate commit for details.
我们可以使用以下Sort参数创建Pageable对象:
我们也可以准备HQL:
We can create Pageable object with following Sort parameter:
We can prepare HQL as well:
这是我(Pascal Thivent)对课程的更新:
这解决了问题:
另外,这里介绍了如何在 JPA (hibernate) 中使用它:
我已经在 postgres 上对此进行了测试,它修复了“空值高于我们遇到的非空问题。
Here's my update to the class by (Pascal Thivent):
This fixes the problem:
Also here's how you can use this within JPA (hibernate):
I've tested this on postgres and it fixes the 'nulls are higher than non-nulls' issue that we were having.
另一种变体,如果您动态创建 SQL 并且不使用 Criteria API:
ORDER BY COALESCE(,'0') [ASC|DESC]
这适用于 varchar 或数字列。
Another variant, if you create SQL on the fly and don't use Criteria API:
ORDER BY COALESCE(,'0') [ASC|DESC]
This works either for varchar or numeric columns.
对于未来的旅行者...我通过覆盖 Hibernate 方言解决了这个问题。我需要在 CriteriaQuery 中默认先为 asc 添加 null,最后为 desc 添加 null,但由于某种原因不支持。 (它在旧版 CriteriaAPI 中受支持)
For future travellers... I solved this by overriding the Hibernate dialect. I needed to add null first for asc and null last for desc by default in CriteriaQuery, which is for some reason not supported. (It's supported in legacy CriteriaAPI)
似乎有为此打开的更改请求/错误票
There appears to be a change request/bug ticket open for this
如前所述,此功能已在 Hibernate 4.2.x 和 4.3.x 版本中实现。
它可以用作例如:
Hibernate v4.3 javadocs are less omissive 此处。
This feature has been implemented during Hibernate 4.2.x and 4.3.x releases as previously mentioned.
It can be used as for example:
Hibernate v4.3 javadocs are less omissive here.