pagehelper的分页查询
1.需要先导入一个包
<!-- 分页助手启动器 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>${pageHelper.starter.version}</version>
</dependency>
2.controller层
需要完全支持Rest风格,所有需要用ResponseEntity
@RestController
@RequestMapping("brand")
public class BrandController {
@Autowired
private BrandService brandService;
/**
* 分页查询品牌
* @param page
* @param rows
* @param sortBy
* @param desc
* @param key
* @return
*/
@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 = this.;
// if (result == null || result.getItems().size() == 0) {
// return new ResponseEntity<>(HttpStatus.NOT_FOUND);
// }
return ResponseEntity.ok(brandService.queryBrandByPageAndSort(page,rows,sortBy,desc, key));
}
}
3.service层
@Service
public class BrandService {
@Autowired
private BrandMapper brandMapper;
public PageResult<Brand> queryBrandByPageAndSort(
Integer page, Integer rows, String sortBy, Boolean desc, String key) {
// 开始分页
PageHelper.startPage(page, rows);
// 过滤
Example example = new Example(Brand.class);
if (StringUtils.isNotBlank(key)) {
example.createCriteria().andLike("name", "%" + key + "%")
.orEqualTo("letter", key);
}
if (StringUtils.isNotBlank(sortBy)) {
// 排序
String orderByClause = sortBy + (desc ? " DESC" : " ASC");
example.setOrderByClause(orderByClause);//创建SQL语句
}
// 查询
Page<Brand> pageInfo = (Page<Brand>) brandMapper.selectByExample(example);
if(CollectionUtils.isEmpty(pageInfo)){
throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
}
//解析分页数据
PageInfo<Brand> info = new PageInfo<>(pageInfo);
// 返回结果
return new PageResult<>(info.getTotal(), pageInfo);
}
}
需要查看SQL语句还需要添加mybatis的一个配置文件
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl