这里主要讲述PageHelper中PageInfo的使用注意事项:
PageInfo()中参数传递list的时候该list一定是要sql执行结果返回的list否则会分页错误。
@Override
public ServerResponse<PageInfo> searchProductByNameAndCategoryIds(String productName,Integer categoryId, int pageNum, int pageSize,String orderBy) {
//判断名称是否为空
if(StringUtils.isBlank(productName) && categoryId == null){
return ServerResponse.createByErrorMessage("参数错误");
}
//用来盛放种类ID的容器
List<Integer> categoryIdList = new ArrayList<Integer>();
//单独判断cateogryId
if(categoryId != null){
//获得该对象
Category category = categoryMapper.selectByPrimaryKey(categoryId);
if(category == null && StringUtils.isBlank(productName)){
//没有命中数据库中的内容,但是也要有分页的内容
PageHelper.startPage(pageNum,pageSize);
List<ProductListVo> pvo = Lists.newArrayList();
PageInfo pageInfo = new PageInfo(pvo);
return ServerResponse.createBySuccess(pageInfo);
}
//需要用到递归算法来查询所有子节点
categoryIdList = iCategoryService.getThisCategoryChildCategories(categoryId).getData();
}
if(StringUtils.isNoneBlank(productName)){
productName = new StringBuilder().append("%").append(productName).append("%").toString();
}
//开始分页
PageHelper.startPage(pageNum,pageSize);
//动态排序
if(StringUtils.isNotBlank(orderBy)){
if(Const.productOrder.productOrder.contains(orderBy)){
String[] orderByArray = orderBy.split("_");
//orderBy方法的格式为orderBy("price asc")
PageHelper.orderBy(orderByArray[0] + " " + orderByArray[1]);
}
}
//获得商品的列表 因为pagehelper.startPage()以后会寻找执行SQL语句的进程 找到之后他把List对象置为Page对象
List<Product> productList = productMapper.selectByProductNameAndCategoryIds(StringUtils.isNotBlank(productName)? productName : null ,categoryIdList.size() == 0 ? null:categoryIdList);
List<ProductListVo> productListVos = Lists.newArrayList();
for(Product product:productList){
ProductListVo productListVo = assembleProductListVo(product);
productListVos.add(productListVo);
}
PageInfo pageInfo = new PageInfo(productList);
pageInfo.setList(productListVos);
return ServerResponse.createBySuccess(pageInfo);
}
}
//开始分页
PageHelper.startPage(pageNum,pageSize);
//动态排序
if(StringUtils.isNotBlank(orderBy)){
if(Const.productOrder.productOrder.contains(orderBy)){
String[] orderByArray = orderBy.split("_");
执行到此处时候进入PageHelper方法:
public static <E> Page<E> startPage(int pageNum, int pageSize, boolean count, Boolean reasonable, Boolean pageSizeZero) {
Page<E> page = new Page<E>(pageNum, pageSize, count);
page.setReasonable(reasonable);
page.setPageSizeZero(pageSizeZero);
//当已经执行过orderBy的时候
Page<E> oldPage = SqlUtil.getLocalPage();
if (oldPage != null && oldPage.isOrderByOnly()) {
page.setOrderBy(oldPage.getOrderBy());
}
SqlUtil.setLocalPage(page);
return page;
注意到这里有个SqlUtil 类,可以进去看看它里面到底有什么东西:
}
public class SqlUtil implements Constant {
private static final ThreadLocal<Page> LOCAL_PAGE = new ThreadLocal<Page>();
//params参数映射
private static Map<String, String> PARAMS = new HashMap<String, String>(5);
//request获取方法
private static Boolean hasRequest;
private static Class<?> requestClass;
private static Method getParameterMap;
里面包括很多的静态方法和一些属性
包括很重要的LocalThread