开发者

get max value record from table in hibernate

开发者 https://www.devze.com 2023-01-17 04:28 出处:网络
How t开发者_StackOverflow社区o get max value record from table in hibernate?You could use a projection:

How t开发者_StackOverflow社区o get max value record from table in hibernate?


You could use a projection:

Criteria criteria = session
    .createCriteria(Person.class)
    .setProjection(Projections.max("age"));
Integer maxAge = (Integer)criteria.uniqueResult();


AFAIK, Projections will only retrieve a subset of the columns (or is it just one column?) you want.

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

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.


Use the max(...) aggregate function:

select max(cat.weight) from Cat cat

Reference

  • Hibernate Core Reference Guide
    • 14.7. Aggregate functions


You could use sub-query:

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

精彩评论

暂无评论...
验证码 换一张
取 消