从hibernate中的表中获取最大值记录

Gan*_*thy 29 java orm hibernate

如何在hibernate中从表中获取最大值记录?

Dar*_*rov 56

您可以使用投影:

Criteria criteria = session
    .createCriteria(Person.class)
    .setProjection(Projections.max("age"));
Integer maxAge = (Integer)criteria.uniqueResult();
Run Code Online (Sandbox Code Playgroud)

  • 这将获得感兴趣的字段的最大*值*,而不是包含最大值的记录(对象). (5认同)

小智 25

AFAIK,Projections只会检索您想要的列的子集(或者只是一列?).

如果您的数据对象是这样的:

class Person {
    private String id;
    private String name;
    private int age;
    ...
}
Run Code Online (Sandbox Code Playgroud)

并希望表中最老的人,以下似乎工作:

...
Person oldest = 
    (Person) session.createCriteria(Person.class)
    .addOrder(Order.desc("age"))
    .setMaxResults(1)
    .uniqueResult();
...
Run Code Online (Sandbox Code Playgroud)

Hibernate日志(带show_sql,format_sqluse_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 <= ?
Run Code Online (Sandbox Code Playgroud)

这似乎是正确的.请注意,这是在带有Oracle 11 XE的Hibernate 3.3.2上.

  • 我不认为这是一个很好的解决方案.因为您必须订购所有记录才能找到最老的人.此解决方案可能会导致大型表中的性能问题. (3认同)

Pas*_*ent 7

使用max(...)聚合函数:

select max(cat.weight) from Cat cat
Run Code Online (Sandbox Code Playgroud)

参考


kan*_*nda 5

您可以使用子查询:

SELECT * FROM Employee WHERE age IN (SELECT MAX(age) age FROM Employee)