Java 从休眠中的表中获取最大值记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3743677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get max value record from table in hibernate
提问by Ganesamoorthy
How to get max value record from table in hibernate?
如何从休眠中的表中获取最大值记录?
回答by Darin Dimitrov
You could use a projection:
您可以使用投影:
Criteria criteria = session
.createCriteria(Person.class)
.setProjection(Projections.max("age"));
Integer maxAge = (Integer)criteria.uniqueResult();
回答by Pascal Thivent
Use the max(...)
aggregate function:
使用max(...)
聚合函数:
select max(cat.weight) from Cat cat
Reference
参考
- Hibernate Core Reference Guide
- Hibernate 核心参考指南
回答by Ravi Mundoli
AFAIK, Projections will only retrieve a subset of the columns (or is it just one column?) you want.
AFAIK,投影只会检索您想要的列的子集(或者只是一列?)。
If your data object is like so:
如果您的数据对象是这样的:
class Person {
private String id;
private String name;
private int age;
...
}
and want the oldest person in the table, the following seems to work:
并想要表中最年长的人,以下似乎有效:
...
Person oldest =
(Person) session.createCriteria(Person.class)
.addOrder(Order.desc("age"))
.setMaxResults(1)
.uniqueResult();
...
The Hibernate log (with show_sql
, format_sql
, and use_sql_comments
all set to true
) shows
Hibernate 日志(带有show_sql
、format_sql
和use_sql_comments
都设置为true
)显示
select
*
from
( /* criteria query */ select
this_.ID as ID1_12_0_,
this_.NAME as NAME_12_0_,
this_.AGE as AGE_12_0_
from
PERSON this_
order by
this_.AGE desc )
where
rownum <= ?
Which seems correct. Note that this is on Hibernate 3.3.2 with Oracle 11 XE.
这似乎是正确的。请注意,这是在带有 Oracle 11 XE 的 Hibernate 3.3.2 上。
回答by kang sanda
You could use sub-query:
您可以使用子查询:
SELECT * FROM Employee WHERE age IN (SELECT MAX(age) age FROM Employee)
SELECT * FROM Employee WHERE age IN (SELECT MAX(age) age FROM Employee)