1、导入jar包
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
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、mapper
import tk.mybatis.mapper.common.Mapper;
public interface BrandMapper extends Mapper<Brand> {
}
4、service
@Service
public class BrandService {
@Autowired
private BrandMapper brandMapper;
public PageResult<Brand> queryBrandByPage(Integer page, Integer rows, String sortBy, Boolean desc, String key) {
//分页
PageHelper.startPage(page, rows);
//过滤
Example example= new Example(Brand.class);
if(StringUtils.isNotBlank(key)){
// select * from tb_breand where name like '%key%' or letter='x' order by id desc
example.createCriteria().orLike("name","%"+key+"%").orEqualTo("letter",key.toUpperCase());
}
//排序
if(StringUtils.isNotBlank(sortBy)){
String orderByClase=sortBy + (desc ? " DESC" : " ASC");
example.setOrderByClause(orderByClase);
}
//查询
List<Brand> list = brandMapper.selectByExample(example);
if(CollectionUtils.isEmpty(list)){
throw new LyException(ExceptionEnums.BRAND_NOT_FOND);
}
PageInfo<Brand> info = new PageInfo<>(list);
return new PageResult<>(info.getTotal(),list);
}
}
5、controller
@GetMapping("page")
public ResponseEntity<PageResult<Brand>> queryBrandByPage(
@RequestParam(value = "page",defaultValue = "1")Integer page,
@RequestParam(value = "rows",defaultValue = "5")Integer rows,
@RequestParam(value = "sortBy",required = false)String sortBy,
@RequestParam(value = "desc",defaultValue = "false")Boolean desc,
@RequestParam(value = "key",required = false)String key
){
PageResult<Brand> result= brandService.queryBrandByPage(page,rows,sortBy,desc,key);
return ResponseEntity.ok(result);
}
6、启动类
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@EnableEurekaClient
@MapperScan("com.leyou.item.mapper")
public class lyItemApplication {
public static void main(String[] args) {
SpringApplication.run(lyItemApplication.class);
}
}
还可以额外打印sql日志
yml里配置
mybatis:
type-aliases-package: com.leyou.user.pojo
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl