简体   繁体   中英

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:

  • I want to use Criteria API and avoid native queries - I can use native queries but do not want to get rid of Criteria in general,

  • avoid processing returned list so that it returns only range of results which I think is meaningless and not efficient.

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();

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM