配置bean:
//mybatisplus自带的分页插件
@Configuration
public class MyBatisPlusConfig {
@Bean
public PaginationInterceptor createPaginationInterceptor() {
return new PaginationInterceptor();
}
}
controller层:
// POST /article/search/{page}/{size} 文章分页
@RequestMapping(value = "search/{page}/{size}", method = RequestMethod.POST)
//之前接受文章数据,使用pojo,但是现在根据条件查询
//而所有的条件都需要进行判断,遍历pojo的所有属性需要使用反射的方式,成本较高,性能较低
//直接使用集合的方式遍历,这里接受数据改为Map集合
public Result findByPage(@PathVariable Integer page,
@PathVariable Integer size,
@RequestBody Map<String, Object> map) {
//根据条件分页查询
Page<Article> pageData = articleService.findByPage(map, page, size);
//封装分页返回对象
PageResult<Article> pageResult = new PageResult<>(
pageData.getTotal(), pageData.getRecords()
);
//返回数据
return new Result(true, StatusCode.OK, "查询成功", pageResult);
}
service:
public Page<Article> findByPage(Map<String, Object> map, Integer page, Integer size) {
//设置查询条件
EntityWrapper<Article> wrapper = new EntityWrapper<>();
Set<String> keySet = map.keySet();
for (String key : keySet) {
// if (map.get(key) != null) {
// wrapper.eq(key, map.get(key));
// }
//第一个参数是否把后面的条件加入到查询条件中
//和上面的if判断的写法是一样的效果,实现动态sql
wrapper.eq(map.get(key) != null, key, map.get(key));
}
//设置分页参数
Page<Article> pageData = new Page<>(page, size);
//执行查询
//第一个是分页参数,第二个是查询条件
List<Article> list = articleDao.selectPage(pageData, wrapper);
pageData.setRecords(list);
//返回
return pageData;
}
分页的实体类:
/**
* 分页
* @param <T>
*/
public class PageResult<T> {
private Long total;
private List<T> rows;
public PageResult() {
}
public PageResult(Long total, List<T> rows) {
this.total = total;
this.rows = rows;
}
public Long getTotal() {
return total;
}
public void setTotal(Long total) {
this.total = total;
}
public List<T> getRows() {
return rows;
}
public void setRows(List<T> rows) {
this.rows = rows;
}
@Override
public String toString() {
return "PageResult{" +
"total=" + total +
", rows=" + rows +
'}';
}
}