Sinny
Sinny

Reputation: 167

How to limit results obtained by hibernate criteria API?

Let's suppose we have a Person class that is a simple hibernate entity. We have a DAO that has a method which retrieves all Person rows that have names listed in names list:

@Transactional
public List<Person> getPersons(List<String> personNames) {

ArrayList<Criterion> locationCriterions = new ArrayList<Criterion>();

if(personNames == null) {
       return new ArrayList<Person>();
}

Criterion [] arrayOfPersonCriterions = new Criterion 
[personNames.size()];

   int currentIndex = 0;

   for(String currentPersonName : personNames) {   
   arrayOfPersonCriterions[currentIndex](Restrictions.eq("name", 
   currentPersonName));
   currentIndex++;
   }     

   Criterion personFinalCriterion = Restrictions.or(arrayOfPersonCriterions);
   Session currentSession = sessionFactory.getCurrentSession();
   Criteria criteria = currentSession.createCriteria(Person.class);

   return (List<Person>)criteria.add(personFinalCriterion).list();

} 

Question: How can I limit the amount of retrieved results - as in SQL where we can use LIMIT X, Y query text?

Please note:

Upvotes: 1

Views: 4121

Answers (2)

v.ladynev
v.ladynev

Reputation: 19956

You can use two methods of the Criteria

criteria.setFirstResult(indexOfTheFirstRecord) to specify the first record (started from 0) criteria.setMaxResults(numberOfTheRecords) to specify count of the records

For simplicity you can use this class

public class Pagination {

    public static final Pagination EMPTY = new Pagination(0, 0);

    /** Page index, begins from 0. */
    private final int pageIndex;

    /** Objects on page count. */
    private final int pageSize;

    public Pagination(int pageIndex, int pageSize) {
        this.pageIndex = pageIndex;
        this.pageSize = pageSize;
    }

    public void addToCriteria(Criteria criteria) {
        if (this == EMPTY) {
            return;
        }
        criteria.setMaxResults(pageSize);
        criteria.setFirstResult(pageIndex * pageSize);
    }

}

Example

To get the second page (pageIndex = 1) with size 10 (records with startIndex = 10, endIndex = 19)

final int pageIndex = 1;
Pagination pagination = new Pagination(pageIndex, 10);
pagination.addToCriteria(criteria);

Upvotes: 1

NullPointerException
NullPointerException

Reputation: 3804

You can set use setFirstResult to skip the records and setMaxResults to fetch the number of records from that point.

Criteria criteria = session.createCriteria(Foo.class);
criteria.setFirstResult(0);
criteria.setMaxResults(pageSize);
List<Foo> firstPage = criteria.list();

Upvotes: 2

Related Questions