springboot+mybatisPlus中分页条件查询

配置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 +
                '}';
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值