0

If I have a class called Person as

public class Person{
  private int id;
  private int age;
}

How can I get the person object with max age?

when I use criteria.setProjection(Projections.max("age) ), it will return me the max age, and then I should find the entry of the person with this age.

Can I skip find the max age? And get the person with max age directly. It may looks like,

person = criteria.somehow.setProjection().somehow.setMaxResults(1).uniqueResult();

I'm trying find out the way to do this, because I concerned if I do twice search in hibernate, it will waste my performance time.

Neil
  • 2,714
  • 11
  • 29
  • 45
  • 1
    Seems to me this is duplicate of [Get record with max id, using Hibernate Criteria](http://stackoverflow.com/questions/3900105/get-record-with-max-id-using-hibernate-criteria). – Mick Mnemonic Aug 04 '15 at 23:31
  • I'd like to get Person object with max age – Neil Aug 05 '15 at 15:13

1 Answers1

0

Could you please try following code :

Criteria cr = session.createCriteria(Person.class);
cr.setProjection(Projections.projectionList()
        .add(Projections.max("age")));

If above does not work you can do this :

 Person p= (Person) session.createCriteria(Person.class)
.addOrder(Order.desc("age"))
.setMaxResults(1)
.uniqueResult();