商品分页查询PageHelper使用
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import tk.mybatis.mapper.entity.Example;
import org.springframework.beans.BeanUtils;
import java.util.stream.Collectors;
public PageResult<SpuBo> querySpuByPage(String key, Boolean saleable, Integer page, Integer rows) {
// 1. 设置分页参数
PageHelper.startPage(page, rows);
// 2. 设置查询条件
Example example = new Example(Spu.class);
Example.Criteria criteria = example.createCriteria();
// 先给key判空
if (StringUtils.isNotBlank(key)) {
// title是通过key去匹配查询的数据库中的字段, 可自定义
criteria.andLike("title", "%" + key + "%");
}
criteria.andEqualTo("saleable", saleable);
// 3. 执行查询
List<Spu> spus = this.spuMapper.selectByExample(example);
// spus.forEach(sup -> { // .forEach返回原来的数组, .stream.map返回一个新数组
List<SpuBo> spuBos = spus.stream().map(spu -> {
SpuBo spuBo = new SpuBo();
// 3.1属性对拷
BeanUtils.copyProperties(spu, spuBo);
// 3.2 设置分类名称 cname -> categoryName
List<String> names = this.categoryService.queryNamesByIds(
Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
spuBo.setCname(StringUtils.join(names, " > "));
// 3.3 设置品牌名称 bname -> brandName
Brand brand = this.brandMapper.selectByPrimaryKey(spu.getBrandId());
spuBo.setBname(brand.getName());
return spuBo;
}).collect(Collectors.toList());
// 4. 返回查询结果
PageInfo<Spu> pageInfo = new PageInfo<>(spus);
return new PageResult<>(pageInfo.getTotal(), pageInfo.getPages(), spuBos);
}
PageResult实体类
import java.util.List;
public class PageResult<T> {
// 总条数
private Long total;
// 总页数
private Integer totalPage;
// 当前页的数据集合
private List<T> items;
public PageResult() {
}
public PageResult(Long total, List<T> items) {
this.total = total;
this.items = items;
}
public PageResult(Long total, Integer 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 Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public List<T> getItems() {
return items;
}
public void setItems(List<T> items) {
this.items = items;
}
}
Controller
import org.springframework.http.ResponseEntity;
@GetMapping("spu/page")
public ResponseEntity<PageResult<SpuBo>> querySpuByPage(
@RequestParam(value = "key", required = false) String key,
@RequestParam(value = "saleable", defaultValue = "true") Boolean saleable,
@RequestParam(value = "page", defaultValue = "1") Integer page,
@RequestParam(value = "rows", defaultValue = "5") Integer rows
) {
PageResult<SpuBo> result = this.goodsService.querySpuByPage(key, saleable, page, rows);
return ResponseEntity.ok(result);
}