Search code examples
javaspringhibernatecriteriahibernate-criteria

Hibernate : Criteria ignoring fetchSize parameter and fetching more rows than asked


I am working on a Spring-MVC application in which I have a search function written using Criteria. FOr paginated search, I get from front-end the firstResult and fetchSize as the parameter. Unfortunately, Criteria is ignoring them and returning a huge list(around 1000 rows) when asked only for 20 rows. What is going wrong?

Code :

  System.out.println("Fetch size is "+fetchSize);
        System.out.println("First result is "+firstResult);
Criteria andCriteria = session.createCriteria(Host.class);
            Conjunction and = Restrictions.conjunction();
            if((studentSearchHistory.getCity()!=null) && (!(studentSearchHistory.getCity().isEmpty()))) {
                and.add(Restrictions.ilike("city", studentSearchHistory.getCity()));
            }
//Other search conditions
    andCriteria.setFetchSize(fetchSize);
    andCriteria.setFirstResult(firstResult);
    andCriteria.add(and);
    hostList.addAll(andCriteria.list());
  if(hostList != null){
     System.out.println("Host list size is "+hostList.size());
   }

Output :

Fetch size is 10
First result is 0
Host list size is 1003

What am I doing wrong? THank you.


Solution

  • Maybe you should using setMaxResults here.

    Here is a comparation for these two methods.