spring 想用 HQL 只获取 5 条记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6042004/
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-09-08 04:30:02  来源:igfitidea点击:

Want to fetch only 5 records with HQL

hibernatespringhql

提问by Sagar

Possible Duplicate:
How do you do a limit query in HQL

可能的重复:
你如何在 HQL 中进行限制查询

I am new to HQL. I have following working HQL query:

我是 HQL 的新手。我有以下工作 HQL 查询:

from Order as o where o.account.profile.userId='abc' order by o.orderID desc

This query returns me list of orders placed by user abc. User can have 0 to 5000+ orders placed in DB. But I want to display only First 5records(Orders). I am using sublist function of java List.

此查询返回用户abc下的订单列表。用户可以在数据库中放置 0 到 5000 多个订单。但我只想显示前 5条记录(订单)。我正在使用 java List 的 sublist 函数。

Can I directly fetch only first 5 records using HQL query? which is more efficient way to write this query?

我可以使用 HQL 查询直接获取前 5 条记录吗?编写此查询的更有效方法是什么?

回答by Florian

You can limit the results returned by a query by calling the setFirstResult()and setMaxResults()functions on the query object before running the query. Like so:

您可以通过在运行查询之前调用查询对象上的setFirstResult()setMaxResults()函数来限制查询返回的结果。像这样:

Query query = session.createQuery("from Order as o where o.account.profile.userId='abc' order by o.orderID desc");
query.setFirstResult(0);
query.setMaxResults(5); 
List result = query.list();

It depends on your DBMS used whether this will be handled in the DBMS directly.

这取决于您使用的 DBMS 是否会直接在 DBMS 中处理。

回答by ssedano

Directly from http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-examples

直接来自http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-examples

Query q = s.createFilter( collection, "" ); // the trivial filter
q.setMaxResults(PAGE_SIZE);
q.setFirstResult(PAGE_SIZE * pageNumber);
List page = q.list();