If a very large set of data is being processed, the code may need to page through the list re-
turned by the query. This has a natural relationship to how the data might be displayed to the
user on a web page: a subset of data is displayed (say 100 rows), along with “next” and “pre-
vious” page links to navigate (page) through the data.
This is accomplished by setting a range on the query:
Query q = em . createNamedQuery ( "selectAll" );
query . setFirstResult ( 101 );
query . setMaxResults ( 100 );
List <? implements
implements StockPrice > = q . getResultList ();
This returns a list suitable for display on the second page of the web application: items
101-200. Retrieving only the range of data needed will be more efficient than retrieving 200
rows and discarding the first 100 of them.
Note that this example uses a named query (the createNamedQuery() method) rather than
an ad hoc query (the createQuery() method). In many JPA implementations, named queries
are faster: the JPA implementation will almost always use a prepared statement with bind
parameters, utilizing the statement cache pool. There is nothing that prevents JPA imple-
mentations from using similar logic for unnamed, ad hoc queries, though implementing that
is more difficult, and the JPA implementation may simply default to creating a new statement
(i.e., a Statement object) each time.