1. 程式人生 > >使用通用mapper按條件查詢分頁資料(包含Example的使用)

使用通用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());