2017-05-31 112 views
0

我試圖從下面的代碼檢索數據庫結果的下一頁。EclipseLink(JPA 2.1)查詢不返回結果,它顯然應該

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行,每個產品都屬於一個類別。 如果我選擇一個類別,如80類產品的類別1。我可以查看每頁20頁的4頁產品。當我嘗試訪問屬於更高類別標識的產品時出現問題。我只能查看前20個結果,但下一頁返回0個結果。 E.g類別15的產品範圍從id=459 to id=794 where id is the primary key

當我從https://localhost:8181/myapp/category?categoryId=15訪問類別頁面時,查詢將返回前20個結果,但點擊底部的更多鏈接返回0個結果。我錯過了什麼?

另請參閱此問題is similar to this

回答

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