You need to enable JavaScript to run this app. Spring Boot应用添加分页功能启动报错问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 09:12:02