package com.leyou.controller; import com.leyou.PageResult; import com.leyou.service.BrandService; import com.pojo.Brand; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("brand") public class BrandController { @Autowired private BrandService brandService; @GetMapping("page") public ResponseEntity<PageResult<Brand>> queryBrand(@RequestParam(value ="page",required = false,defaultValue = "1")int page ,@RequestParam(value ="rows",defaultValue = "5",required = false)int rows, @RequestParam(value = "sortBy",required = false)String sortBy, @RequestParam(value = "desc",required = false) boolean desc, @RequestParam(value = "key",required = false) String key ){ //使用service来进行分页查询 PageResult<Brand> list= this.brandService.queryBrandByPage(page,rows,sortBy,desc,key); //得到查询的结果进行判断再返回 if(list==null){ //如果查询结果是空的话,则可以返回404 return ResponseEntity.notFound().build(); } return ResponseEntity.ok(list); } }
package com.leyou.service; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.leyou.PageResult; import com.leyou.mapper.BrandMapper; import com.pojo.Brand; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import tk.mybatis.mapper.entity.Example; import java.util.List; @Service public class BrandService { @Autowired private BrandMapper brandMapper; public PageResult<Brand> queryBrandByPage(int page, int rows, String sortBy, boolean desc, String key) { //使用分页助手来实现分页查询 //开启分页,第一个参数是当前页数,第二个参数是每页的条数 PageHelper.startPage(page,rows); //使用eaample对象进行查询,则创建一个与需要查询类关联的example对象 Example example = new Example(Brand.class); //实现对查询条件的拼接 if(StringUtils.isNotBlank(key)){ //如果key存在,则实现在查询的后面添上模糊查询 example.createCriteria().andLike("name","%"+key+"%").orEqualTo("letter",key); } if(StringUtils.isNotBlank(sortBy)){ //如果排序对象存在,则需要在后面添上按照传递过来的sortBy和desc进行排序排序 //分页查询的条件就是mysql后面查询条件的拼接 String orderBYclause=sortBy+( desc ? "DESC":"ASC"); example.setOrderByClause(orderBYclause); } //执行查询 //查询出来的结果可以用page<T>来进行封装,可以得到查询的所有结果 Page<Brand> brands = (Page<Brand>) this.brandMapper.selectByExample(example); //返回的结果是pageResult类型 return new PageResult<>(brands.getTotal(),brands); } }