How to get max value record from table in hibernate?
4 Answers
You could use a projection:
Criteria criteria = session
.createCriteria(Person.class)
.setProjection(Projections.max("age"));
Integer maxAge = (Integer)criteria.uniqueResult();
5 Comments
Ganesamoorthy
Criteria criteria = getSession() .createCriteria(Borrower.class) .setProjection(Projections.max("brwrid")); Long maxBrwrid = (Long)criteria.uniqueResult();
Ganesamoorthy
its working fine. but null value returns, if null returns set value is 1 else max+1, how to do it.
Darin Dimitrov
if (maxBrwrid == null) { maxBrwrid = 1; } else { maxBrwrid = maxBrwrid + 1; }Robin Green
This gets the maximum value of the field of interest, not the record (object) containing the maximum value.
shareef
please satisfys my need can you edit and improve the answer with
if (maxBrwrid == null) { maxBrwrid = 1; } else { maxBrwrid = maxBrwrid + 1; } as @Darin DimitrovAFAIK, 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.
1 Comment
Halil
I don't think this one is a good solution. Because you have to order all the records to find the oldest Person. This solution may result in performance problems in large tables.
Use the max(...) aggregate function:
select max(cat.weight) from Cat cat
Reference
- Hibernate Core Reference Guide
Comments
You could use sub-query:
SELECT * FROM Employee WHERE age IN (SELECT MAX(age) age FROM Employee)
1 Comment
Niccolò
I guess that the last occurrence of "age" is a typo..
FROM Employee WHERE age IN (SELECT MAX(age) FROM Employee)