java - hibernate : Criteria ignoring fetchSize parameter and fetching more rows than asked

标签 java spring hibernate criteria hibernate-criteria

我正在开发一个 Spring-MVC 应用程序,其中有一个使用 Criteria 编写的搜索函数。对于分页搜索,我从前端获取firstResult 和fetchSize 作为参数。不幸的是,当只要求 20 行时,Criteria 会忽略它们并返回一个巨大的列表(大约 1000 行)。出了什么问题?

代码:

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

输出:

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

我做错了什么?谢谢。

最佳答案

fetchSize 与查询导出的记录数无关。与获取的记录数有关。

您需要使用setMaxResults限制 hibernate 检索的记录数量。

Set the maximum number of rows to retrieve. If not set, there is no limit to the number of rows retrieved.

setFetchSize仅与 hibernate 如何在内部获取记录组有关(是一种缓存)。

Set a fetch size for the underlying JDBC query.

Statement的描述来看:

Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when more rows are needed for ResultSet objects genrated by this Statement. If the value specified is zero, then the hint is ignored. The default value is zero.

关于java - hibernate : Criteria ignoring fetchSize parameter and fetching more rows than asked,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39408846/

相关文章:

java - Jira 6.1.6 Java REST api - 无法设置自定义下拉值

java - 用于集成测试的 Spring Data JPA 存储库接线不起作用

java - 使用 Ribbon 自动重试(无 zuul): not working + wrong documentation?

java - Spring事务性注解应该放在哪里,在哪一层?

java - Springboot findBy List <String> hibernate @Query

Java套接字文件发送

java - java中存储数据的类,模拟mysql表

java - Spring 中的自定义身份验证

java - 如何在 Spring MVC 中处理 URL 和 @RequestMapping

java - 测试 Hibernate 查询