786543214
786543214

Reputation: 855

Hibernate setMaxresults with Detachedcriteria will not work

Here is my question I have a DetachedCriteria as follows where I need only one record with max ID need to fetch. But as of now I am fetched list of records as list and from there I am getting record with max Id using for loop.

DetachedCriteria criteria = DetachedCriteria.forClass(ContactList.class);
        criteria.add(Restrictions.eq("userId", id));

List contactList = getHibernateTemplate().findByCriteria(criteria);

From contactList I am finding the recored with max Id with seperate loop.

My question is, Is there any way to add that restriction in DetachedCriteria itself. I tried setMaxResults, but its not working.

Upvotes: 2

Views: 1483

Answers (1)

MayurB
MayurB

Reputation: 3649

DetachedCriteria criteria = DetachedCriteria.forClass(ContactList.class);
criteria.add(Restrictions.eq("userId", id)).setProjection(Projections.max("useId"));

List contactList = getHibernateTemplate().findByCriteria(criteria);

Projection.max will retriev max value record from table in hibernate

Upvotes: 2

Related Questions