jpa 分頁功能1

1.service 層
public Result findAllAdvertise(Page page,String categoryId){
    	StringBuffer sql1 = new StringBuffer();
    	StringBuffer sql2 = new StringBuffer();
    	sql1.append("select count(*) from Advertise a");
    	sql2.append("from Advertise a where 1=1");
    	if(categoryId != null && !categoryId.equals("")){
    		sql1.append(" where a.categoryId = ?");
    		sql2.append(" and a.categoryId = ?");
    		sql2.append(" order by a.createtime desc");
    		
    		page = PageUtil.createPage(page, (Long) em.createQuery(sql1.toString()).setParameter(1,categoryId).getSingleResult());
    		return new Result(page,em.createQuery(sql2.toString()).setParameter(1,categoryId).setFirstResult(page.getBeginIndex()).setMaxResults(page.getEveryPage()).getResultList());
    	}else{
    		sql2.append(" order by a.createtime desc");
    		page = PageUtil.createPage(page, (Long) em.createQuery(sql1.toString()).getSingleResult());
        	return new Result(page,em.createQuery(sql2.toString()).setFirstResult(page.getBeginIndex()).setMaxResults(page.getEveryPage()).getResultList());
    	}
    }

2.action 層

@RequestMapping("/webadmin/AderviseList.htm")
 public String AderviseList(HttpServletRequest request){
  String categoryId = request.getParameter("categoryId");
  if(categoryId ==null ||categoryId.equals("")){
   categoryId = (String)request.getAttribute("categoryId");
  }
  String currpage =request.getParameter("page");
  if(currpage == null || currpage.equals("")){
   currpage ="1";
  }
  Page page = new Page(20);
  page.setCurrentPage(new Integer(currpage));
  
  Result list = aderviseBiz.findAllAdvertise(page, categoryId);
  request.setAttribute("aderviselist", list);
  
  //查詢所有類別
  List categoryList = aderviseBiz.findAllAdvertiseCategory();
  request.setAttribute("categoryList",categoryList);
     request.setAttribute("categoryId", categoryId);
  return "/webadmin/AderviseList.vm";
 }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章