使用 Hibernate Criteria 获取具有最大 id 的记录
使用 Hibernate 的 Criteria API,我想选择表中给定列具有最大值的记录。
我尝试使用 投影,< a href="http://docs.jboss.org/hibernate/core/4.3/javadocs/org/hibernate/Criteria.html#createAlias(java.lang.String,%20java.lang.String)" rel="noreferrer ">为 max(colunName)
创建别名,然后在 restrictions.eq()
,但是它一直告诉我“号码无效”。
使用 Hibernate 执行此操作的正确方法是什么?
Using Hibernate's Criteria API, I want to select the record within a table with the maximum value for a given column.
I tried to use Projections, creating an alias for max(colunName)
, then using it in restrictions.eq()
, but it keeps telling me "invalid number".
What's the correct way to do that with Hibernate?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您可以使用
DetachedCriteria
来表达子查询,如下所示:参考资料
You can use a
DetachedCriteria
to express a subquery, something like this:References
我发现同时使用
addOrder
和setMaxResults
对我有用。使用 MySQL 方言,这会生成一个类似这样的 SQL 准备语句(剪掉一些字段):
我不确定此解决方案是否对 MySQL 以外的方言有效。
I found that using
addOrder
andsetMaxResults
together worked for me.Using the MySQL dialect, this generates a SQL prepared statement about like this (snipping out some of the fields):
I am not sure if this solution would be effective for dialects other than MySQL.
仅使用
并获取第一个结果:)
Use
and fetch just the first result :)
HQL:
未经测试。您的数据库需要理解 where 子句中的子选择。
懒得去了解是否/如何使用标准 api 来表达这样的子选择。当然,您可以执行两个查询:首先获取最大 id,然后获取具有该 id 的实体。
HQL:
Untested. Your database needs to understand subselects in the where clause.
Too lazy to find out if/how such a subselect can be expressed with the criteria api. Of course, you could do two queries: First fetch the max id, then the entity with that id.
更清洁的解决方案也是:
The cleaner solution would also be :
完全使用独立标准来完成此操作(因为我喜欢在没有会话的情况下构建独立标准)
To do it entirely with Detached Criteria (because I like to construct the detached criteria without a session)
对于hibernate中的
max()
函数:For the
max()
function in hibernate: