Java 限制 JPQL 中的结果数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3479128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:08:51  来源:igfitidea点击:

Limit number of results in JPQL

javajpajpql

提问by coubeatczech

How it is possible to limit the number of results retrieved from a database?

如何限制从数据库中检索到的结果数量?

select e from Entity e /* I need only 10 results for instance */

采纳答案by Nayan Wadekar

You can try like this giving 10 results to be fetched explicitly.

您可以尝试像这样给出 10 个要显式获取的结果。

entityManager.createQuery(JPQL_QUERY)
             .setParameter(arg0, arg1)
             .setMaxResults(10)
             .getResultList();

It will automatically create native query in back-end to retrieve specific number of results, if the backend supports it, and otherwise do the limit in memory after getting all results.

如果后端支持,它将自动在后端创建原生查询以检索特定数量的结果,否则在获取所有结果后在内存中进行限制。

回答by Tharaka

You can set an offset too using setFirstResult()

您也可以使用 setFirstResult() 设置偏移量

    em.createNamedQuery("Entity.list")
      .setFirstResult(startPosition)
      .setMaxResults(length);