You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot通过ID查询客户数据报错:ID不存在问题求助

问题排查与解决:Spring Boot通过客户ID查询报错EntityNotFoundException

问题描述

调用接口http://localhost:8080/customer/2获取客户信息时,系统抛出异常:

jakarta.persistence.EntityNotFoundException: Entity with ID 2 not found at com.example.crud.service.BaseService.baseFindById(BaseService.java:23)

排查方向与解决方法

1. 数据库中无对应ID的记录

  • 排查:直接查询数据库customers表,执行SQL语句:
    SELECT * FROM customers WHERE customerid = 2;
    
    若返回空结果,说明确实不存在ID为2的客户数据。
  • 解决:
    • 通过新增接口添加ID为2的客户数据,或使用现有存在的ID进行测试;
    • 因实体类主键用GenerationType.IDENTITY自增策略,需确认数据库自增序列的当前值是否覆盖到2,避免手动插入ID导致序列不一致。

2. 实体类与数据库表映射不匹配

  • 排查:
    • 确认数据库表名称为customers,与实体类@Table(name = "customers")配置一致;
    • 检查主键字段:实体类customerId对应数据库customerid字段,@Column(name = "customerid")配置正确,同时确认数据库字段类型为INT(与实体类Integer匹配);
    • 验证Lombok的@Data注解是否生效,确保生成了customerId的getter/setter方法,保证JPA能正常访问字段。
  • 解决:
    • 修正表名、字段名或类型的不匹配项;
    • 若Lombok未生效,手动添加customerId的getter/setter方法。

3. 接口路径匹配问题

  • 排查:
    • 控制器类@RequestMapping("/customer/")与@GetMapping("/{id}")组合后,实际接口路径为/customer//{id}(双斜杠),虽Spring会自动处理为单斜杠,但可能存在解析异常;
    • 检查Postman请求路径是否存在拼写错误。
  • 解决:
    • 调整控制器路径配置,将@RequestMapping("/customer")(去掉末尾斜杠)搭配@GetMapping("/{id}"),使路径变为规范的/customer/{id};
    • 确保Postman请求路径为http://localhost:8080/customer/2(无多余斜杠)。

4. 主键查询逻辑问题

  • 排查:
    • 检查BaseService的baseFindById方法,确认repository.findById(id)执行逻辑正确;
    • 验证CustomerRepository继承JpaRepository<Customers, Integer>的泛型类型是否正确(主键类型为Integer)。
  • 解决:
    • 在baseFindById方法中添加日志打印,确认查询ID和结果:
      @Transactional (readOnly = true)
      public T baseFindById (ID id){
          System.out.println("查询ID:" + id);
          Optional<T> entity = repository.findById(id);
          System.out.println("查询结果:" + entity);
          if(entity.isEmpty()){
              throw new EntityNotFoundException("Entity with ID " + id + " not found");
          }
          return entity.get();
      }
      
    • 若使用自定义查询,确保查询条件正确关联主键字段。

内容的提问来源于stack exchange,提问作者Mahadi Hasan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 09:07:13