我正在尝试使用以下代码从数据库中检索下一页结果。
public Collection<Product> getCategoryProducts(Category selectedCategory, String start) {
Query query = em.createQuery("SELECT p FROM Product p WHERE p.categoryId = :categoryId")
.setParameter("categoryId", selectedCategory)
.setMaxResults(20);
if (null != start) {
query.setFirstResult(Integer.parseInt(start));
}
return query.getResultList();
}
我的产品表有大约1000行,每个产品属于一个类别。
如果我选择类别1的类别,其中包含80个产品。我能够查看4页产品,每个产品有20个产品。当我尝试访问属于更高categoryId的产品时出现问题。我只能查看前20个结果,但下一页返回0结果。
例如,类别15的产品范围为id=459 to id=794 where id is the primary key
。
当我从https://localhost:8181/myapp/category?categoryId=15
访问类别页面时,查询将返回前20个结果,但点击底部https://localhost:8181/myapp/category?categoryId=15&start=478
的更多链接会返回0结果。我错过了什么?
另请参阅此问题is similar to this
答案 0 :(得分:0)
我终于找到了我的错误。显然,我为第一个结果设置的位置应该是page number and the page size
的乘积。在我的情况下,我将第一个结果设置为我正在检索的实体的Id
。作为前几页的结果,结果大小包含ID
,但随着页码数的增加,id
不包含在结果集中。这是一种你不知道的错误,直到你知道你不知道为止。
public Collection<Product> getCategoryProducts(Category selectedCategory, String page) {
int pageSize = 20;
EntityManager entityManager = Persistence.createEntityManagerFactory("techbayPU").createEntityManager();
Query query = entityManager.createQuery("SELECT p FROM Product p WHERE p.categoryId = :categoryId ORDER BY p.id", Product.class);
query.setMaxResults(pageSize);
if (null != page) {
query.setFirstResult(Integer.parseInt(page) * pageSize);
}
query.setParameter("categoryId", selectedCategory);
return query.getResultList();
}