javahibernateormdetachedcriteria

What is the best way to limit results using a DetachedCriteria of Hibernate in Java?


I'm using Hibernate 3.5.6-Final in Java. Since I don't have access to the Hibernate Session, I'm using a DetachedCriteria. So, I would like to know what is the best way to limit the results for a DetachedCriteria (in my case I would like to get only the first row).

Additional info:

The Criteria class has some methods to achieve this, like setMaxResults(int maxResults) or setFirstResult(int firstResult), but the DetachedCriteria doesn't have neither. Again, I can't use the Criteria because I don't have access to the Hibernate's Session.


Solution

  • This is how i am doing it, you have to wrap your result into execute block. EntityMAnager in the example below is org.springframework.orm.hibernate3.HibernateOperations object :

    final DetachedCriteria criteria = DetachedCriteria.forClass(ActivePropertyView.class);
    criteria.add(Restrictions.eq("featured", true));
    List<ActivePropertyView> result = entityManager.execute(
         new HibernateCallback<List<ActivePropertyView>>() {
             @Override
             public List<ActivePropertyView> doInHibernate(Session session) 
                                             throws HibernateException,SQLException {
                     return criteria.getExecutableCriteria(session).setMaxResults(5).list();
             }
         });
    return result;