我在使用pagehelper对列表进行分页时,postman报错如下:
一开始我的代码如下:
@Override
public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
PageBean<Article> pb = new PageBean<>();
PageHelper.startPage(pageNum, pageSize);//分页
Map<String,Object> map = ThreadLocalUtil.get();//获取数据
Integer userId = (Integer)map.get("id");
List<Article> as = articleMapper.list(userId, categoryId, state);//查询
Page<Article> p = (Page<Article>)as;//强转为Page类型
pb.setTotal(p.getTotal());
pb.setItems(p.getResult());
return pb;
}
方案一
在CSDN搜索解决方案,发现问题有可能出现在Page Helper的位置不对。Page Helper只会对最近的一个查询语句进行分页,所以要写在查询语句的上一行。
java.util.ArrayList cannot be cast to com.github.pagehelper.Page-CSDN博客
于是对代码进行如下更改:
@Override
public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
PageBean<Article> pb = new PageBean<>();
//PageHelper.startPage(pageNum, pageSize);//原来的分页
Map<String,Object> map = ThreadLocalUtil.get();//获取数据
Integer userId = (Integer)map.get("id");
PageHelper.startPage(pageNum, pageSize);//分页,移动到这里
List<Article> as = articleMapper.list(userId, categoryId, state);//查询
Page<Article> p = (Page<Article>)as;//强转为Page类型
pb.setTotal(p.getTotal());
pb.setItems(p.getResult());
return pb;
}
结果postman还是报同样的错误
方案二
于是又辗转查阅资料,发现有可能是因为PageHelper的版本不对。于是,我将PageHelper的版本从1.3.0到6.1.0都试过一遍,仍然报错(不过这里发现了一个新的知识点:某些低版本的PageHelper没有StartPage方法)
方案三(最终解决方案)
使用mybatis自带的RowBounds进行分页
@Override
public List<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
//PageBean<Article> pb = new PageBean<>();
//List<Article> as = articleMapper.list(userId, categoryId, state);
//PageHelper.startPage(pageNum, pageSize);
//Page<Article> pg =(Page)articleMapper.list(userId, categoryId, state, rowBounds);
//List<Article>as = pg.getResult();*/
Map<String,Object> map = ThreadLocalUtil.get();
Integer userId = (Integer)map.get("id");
RowBounds rowBounds = new RowBounds(pageNum, pageSize);
List<Article> as = articleMapper.list(userId, categoryId, state, rowBounds);
//只需要再传递一个rowBounds对象
return as;
}
完美解决!
不过RowBounds的性能在大的数据上不如PageHelper(