hibernate 利用Criteria分页查询 例子代码

@Override
public Map<String,Object> findByRequestMap(HashMap requestMap) {
    Integer pageNum = 1;
    if(requestMap.containsKey("page")){
        pageNum = Integer.valueOf((String)requestMap.get("page"));
    }
    Integer pageSize = 10;
    if(requestMap.containsKey("limit")){
        pageSize = Integer.valueOf((String)requestMap.get("limit"));
    }
    Criteria criteria = getSession().createCriteria(SSOAccount.class);
    if (requestMap.containsKey("loginName")) {
        criteria.add(Restrictions.like("loginName", "%" + requestMap.get("loginName") + "%"));
    }
    if (requestMap.containsKey("mobile")) {
        criteria.add(Restrictions.like("mobile", "%" + requestMap.get("mobile") + "%"));
    }
    if (requestMap.containsKey("userName")) {
        criteria.add(Restrictions.like("userName", "%" + requestMap.get("userName") + "%"));
    }
    //可先使用 Projections.rowCount() 来取得总记录数,如下:
   // Long totalNum = (Long)criteria.setProjection(Projections.rowCount()).uniqueResult();
    criteria.setFirstResult((pageNum-1) * pageSize);
    criteria.setMaxResults(pageSize);
    Long totalNum = (Long)criteria.setProjection(Projections.rowCount()).uniqueResult();
   // 然后将 Projection 设为空,再进行正常分页。
    criteria.setProjection(null);
    List<SSOAccount> ssoAccountList = criteria.list();
    Map resultMap = new HashMap<String,Object>();
    resultMap.put("data", ssoAccountList);
    resultMap.put("total", totalNum);
    return resultMap;
}
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页