Spring Boot中如何使用Pageable实现全量记录的分页查询
问题根因与解决方案
你遇到的问题核心是实体映射与查询数据源不匹配,其次需要排查Pageable的配置是否正确,可按以下步骤逐一修复:
1. 修复核心数据源不匹配问题
你当前存储数据用的是Post实体,对应数据库表POST,但分页查询直接操作的是PostInfo实体,其默认对应数据库表POST_INFO,该表无数据自然查询不到分页结果。推荐两种修复方案:
方案A:查询后手动类型转换
将PostRepository定义为操作Post实体的DAO:
public interface PostRepository extends JpaRepository<Post, Long> { }
修改服务层实现方法,将查询到的Post分页对象转换为PostInfo分页对象:
@Override public Page<PostInfo> getPosts(Pageable pageable) { Page<Post> postPage = postRepository.findAll(pageable); // 逐元素转换类型 return postPage.map(post -> { PostInfo info = new PostInfo(); info.setId(post.getId()); info.setTitle(post.getTitle()); return info; }); }
方案B:使用Spring Data投影简化转换
将PostInfo改为接口投影,无需额外实体存储:
// 去掉@Entity等实体注解,改为投影接口 public interface PostInfo { Long getId(); String getTitle(); }
在PostRepository中新增分页查询方法,直接返回投影结果:
public interface PostRepository extends JpaRepository<Post, Long> { Page<PostInfo> findAllBy(Pageable pageable); }
服务层直接调用即可:
@Override public Page<PostInfo> getPosts(Pageable pageable) { return postRepository.findAllBy(pageable); }
2. 检查Pageable自动绑定配置
- 确保项目启动类上添加了
@EnableSpringDataWebSupport注解,才能自动将请求参数封装为Pageable对象 - 接口请求参数默认规则:
page为页码(从0开始,默认0)、size为每页条数(默认20),示例请求:GET /posts?page=0&size=10
3. 排查序列化问题
如果断点确认查询到了数据,但接口返回为空,检查是否自定义了ObjectMapper,需注册Spring Data分页序列化模块:
@Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new SpringDataJacksonModules()); return mapper; }
内容的提问来源于stack exchange,提问作者Karanja
相关产品推荐
相关产品推荐

