在 JPA 中, Query 這一個物件有
setFirstResult(int startPosition)
- setMaxResults(int maxResult)
在 Pro JPA 2 page. 194 提到, 可用 stateful session 來達到用 存放在 http session 中, 讓 jsp or javaServer faces 可以 作到 PageQuery
@Stateful
public class ResultPagerBean implements ResultPager {
@PersistenceContext(unitName="QueryPaging")
private EntityManager em;
private String reportQueryName;
private long currentPage;
private long maxResults;
private long pageSize;
public long getPageSize() {
return pageSize;
}
public long getMaxPages() {
return maxResults / pageSize;
}
public void init(long pageSize, String countQueryName,
String reportQueryName) {
this.pageSize = pageSize;
this.reportQueryName = reportQueryName;
maxResults = em.createNamedQuery(countQueryName, Long.class)
.getSingleResult();
currentPage = 0;
}
public List getCurrentResults() {
return em.createNamedQuery(reportQueryName)
.setFirstResult(currentPage * pageSize)
.setMaxResults(pageSize)
.getResultList();
}
public void next() {
currentPage ;
}
public void previous() {
currentPage--;
if (currentPage < 0) {
currentPage = 0;
}
}
public long getCurrentPage() {
return currentPage;
}
public void setCurrentPage(long currentPage) {
this.currentPage = currentPage;
}
@Remove
public void finished() {}
}
沒有留言:
張貼留言