HQL select range of results

2019-07-19 09:22发布

问题:

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)");

回答1:

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


回答2:

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.