Spring Boot应用添加分页功能启动报错问题咨询
问题诱因
- Repository泛型与返回类型错误:你定义的UserRepository继承了
CrudRepository<Consignment, Integer>,说明操作的实体是Consignment,但方法返回值却写了Page<Example>,这里的Example是Spring Data提供的查询条件工具类,并非你的业务实体类,类型不匹配导致查询生成逻辑异常。 - 方法定义不符合Spring Data JPA命名规则:报错日志明确指向
findConsignmentsByAccount方法,该方法名包含ByAccount,按照规则需要传入对应account属性的参数作为查询条件,但你没有定义该参数,触发参数未绑定的异常。你贴出的代码里只有findByValidIsTrue方法,说明运行的代码存在残留的findConsignmentsByAccount方法,或者编译缓存未清理。 - Repository父类选型错误:CrudRepository本身没有内置分页支持,要实现分页查询应该继承
PagingAndSortingRepository或者JpaRepository。
解决方案
- 清理无效代码:先删除Repository中残留的
findConsignmentsByAccount方法,如果确实需要该查询功能,按照规则补全参数:
// 示例:需要查询指定account的分页数据时的写法 Page<Consignment> findConsignmentsByAccount(String account, Pageable pageable); // 调用时需要传入account参数
- 修正Repository定义:更换父类为支持分页的Repository,修正返回值泛型为实际业务实体类:
package com.example.accessingdatamysql; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import com.example.accessingdatamysql.Consignment; public interface UserRepository extends JpaRepository<Consignment, Integer> { // 返回值泛型改为实际实体类Consignment Page<Consignment> findByValidIsTrue(Pageable pageable); }
- 修正Controller调用逻辑:把分页结果的泛型改为对应的实体类:
@GetMapping(path="/all") @ResponseBody public String getAllUsers() { PageRequest req = PageRequest.of(0,10); // 泛型改为Consignment Page<Consignment> page = userRepository.findByValidIsTrue(req); List<Consignment> nRecords = page.getContent(); Gson json = new Gson(); return json.toJson(nRecords); }
- 清理项目编译缓存,重新启动应用即可。
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

