首先注意导包,导完包后我们新建一个品牌类
@Table(name = "tb_brand")
@Data
public class Brand implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
/**
* 品牌名称
*/
private String name;
/**
* 品牌图片地址
*/
private String image;
/**
* 品牌的首字母
*/
private String letter;
}
再新建一个分页类
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;
}
}
mapper层继承tkmybatis的接口
Service层
@Autowired
private BrandMapper brandMapper;
public PageResult<Brand> pageQuery(Integer page, Integer rows, String sortBy, Boolean desc, String key) {
//开启分页查询
PageHelper.startPage(page, rows);
//过滤
Example example = new Example(Brand.class);
Example.Criteria criteria = example.createCriteria();
if (StringUtils.isNotBlank(key)) {
criteria.andLike("name", "%" + key + "%");
}
//判断字段不为空
if (StringUtils.isNotBlank(sortBy)) {
//desc为true 倒序
example.setOrderByClause(sortBy+(desc ? " Desc" : " ASC")); //注意前面的空格
}
//直接查询并转换为分页条件查询结果
Page<Brand> brands = (Page<Brand>) brandMapper.selectByExample(example);
//封装分页的结果对象
return new PageResult<>(brands.getTotal(), new Long(brands.getPages()), brands);
}
controller层
@Autowired
private BrandServiceImpl brandService;
@GetMapping("page")
public ResponseEntity<PageResult<Brand>> pageQuery(
@RequestParam(value = "page",defaultValue = "1")Integer page,
@RequestParam(value = "rows",defaultValue = "10")Integer rows,
@RequestParam(value = "sortBy",required = false)String sortBy,
@RequestParam(value = "desc",required = false)Boolean desc,
@RequestParam(value = "key",required = false)String key) {
PageResult<Brand> brandPageResult = brandService.pageQuery(page, rows, sortBy, desc, key);
//判断分页数据不为空
if (brandPageResult != null && null != brandPageResult.getItems() && 0!=brandPageResult.getItems().size()) {
return ResponseEntity.ok(brandPageResult);
}
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}