使用通用mapper按条件查询分页数据(包含Example的使用)
1 步骤: 分页 , 添加条件, 返回page对象, 封装为需要的对象
2 一般分页数据需要三个参数: 总页数, 总条数, 对象的集合,
因此可以建立一个通用类,封装上面的三个参数,具体如下:
public class PageResult<T> {
private Long total;// 总条数
private Long totalPage;// 总页数
private List<T> items;// 当前页数据
public PageResult() {
}
public PageResult(Long total, List<T> items) {
this.total = total;
this.items = items;
}
public PageResult(Long total, Long totalPage, List<T> items) {
this.total = total;
this.totalPage = totalPage;
this.items = items;
}
public Long getTotal() {
return total;
}
public void setTotal(Long total) {
this.total = total;
}
public List<T> getItems() {
return items;
}
public void setItems(List<T> items) {
this.items = items;
}
public Long getTotalPage() {
return totalPage;
}
public void setTotalPage(Long totalPage) {
this.totalPage = totalPage;
}
}
3 因此需要返回的数据类型就是PageResult<Goods> (以商品类为例)
// 分页,最多允许查100条
PageHelper.startPage(page, Math.min(rows, 100));
// 创建查询条件
Example example = new Example(Goods.class);
Example.Criteria criteria = example.createCriteria();
// 是否模糊查询
if (StringUtils.isNotBlank(key)) {
criteria.andLike("title", "%" + key + "%");
}
//得到page对象
Page<Goods> pageInfo = (Page<Goods>) this.spuMapper.selectByExample(example);
//封装为pageResult对象
return new PageResult<>(pageInfo.getTotal(),pageInfo.getResult());