当批量查询数据时(例如查询CUSTOMERS表中所有记录),如果数据量很大,会导致无法在用户终端的单个页面上显示所有的查询结果,此时需要对查询结果分页。假如CUSTOMER表中有99条记录,可以在用户终端上分10页来显示结果,每一页最多只显示10个Customer对象,用户既可以导航到下一页,也可以导航到前一页。
Query接口提供了用于分页获取查询结果的方法:
- setFirstResult(int firstResult):设定从哪一个对象开始检索,参数firstResult表示这个对象在查询结果中的索引位置,索引位置的起始值为0。在默认情况下,Query接口从查询结果中的第一个对象,也就是索引位置为0的对象开始检索。
- setMaxResults(int maxResults):设定一次最多检索出的对象数目。在默认情况下,Query接口检索出查询结果中所有的对象。
以下代码从查询结果的起始对象开始,共检索出10个Customer对象,查询结果按照name属性排序:
//采用JPQL检索方式
TypedQuery<Customer> query = entityManager.createQuery(
"from Customer c order by c.name asc",Customer.class);
query.setFirstResult(0);
query.setMaxResults(10);
List<Customer> result = query.getResultList();
//采用QBC检索方式
CriteriaQuery<Customer> criteriaQuery =
criteriaBuilder.createQuery(Customer.class);
Root<Customer> root = criteriaQuery.from(Customer.class );
criteriaQuery.select(root);
javax.persistence.criteria.Order order=
criteriaBuilder.asc(root.get(Customer_.name));
criteriaQuery.orderBy(order); //指定排序方式
TypedQuery<Customer> query=entityManager.createQuery(criteriaQuery);
query.setFirstResult(0);
query.setMaxResults(10);
List<Customer> result=query.getResultList();
如果查询结果中共有99个Customer对象,那么在result中包含10个Customer对象,第1个对象在查询结果中的索引位置为0,第10个对象在查询结果中的索引位置为9。
以下代码从查询结果中索引位置为97的对象开始,共检索出10个Customer对象:
//采用JPQL检索方式
TypedQuery<Customer> query = entityManager.createQuery(
"from Customer c order by c.name asc",Customer.class);
query.setFirstResult(97);
query.setMaxResults(10);
List<Customer> result = query.getResultList();
//采用QBC检索方式
……
TypedQuery<Customer> query=entityManager.createQuery(criteriaQuery);
query.setFirstResult(97);
query.setMaxResults(10);
List<Customer> result = query.getResultList();
如果查询结果中共有99个对象,那么在result中只包含两个Customer对象,它们的索引位置分别为97和98。