HQL select range of results

2019-07-19 09:51发布

What is the correct/efficient way to retrieve a sub set of results from hibernate?

Assuming that products is a table containing a 3000 records.

Session session = SessionFactorys.getSessionFactory().openSession();
Query query = session.createQuery("from products p");
List result = query.list().subList(30, 40);     
session.disconnect();

The code above dose not seem to be very efficient is there a better way, I am trying to find something like.

Query query = session.createQuery("from products p range(30,40)");

2条回答
小情绪 Triste *
2楼-- · 2019-07-19 10:01

Look at setFirstResult and setMaxResults in the javadoc of Query.

Note that these are applied to the rows returned by the JDBC calls, and not to the entities returned by the query. In general, that's equivalent. But it's not if your query fetches a *ToMany association.

查看更多
做自己的国王
3楼-- · 2019-07-19 10:15

Use query.setFirstResult() and query.setMaxResults() but be aware that this of course depends on the ordering of your result set.

Query query = session.createQuery("from products p");
query.setFirstResult(30);
query.setMaxResults(10);
List result = query.list();
查看更多
登录 后发表回答