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语句:
若返回空结果,说明确实不存在ID为2的客户数据。SELECT * FROM customers WHERE customerid = 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
相关产品推荐
相关产品推荐

