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

JPA findById返回null但数据存在的问题求助

问题排查与修复方案

核心问题1:路径变量注解错误

你的控制器中@GetMapping("/services/{id}")定义了路径变量,但参数却用了@RequestParam,这会导致无法正确获取URL中的ID值。应该替换成@PathVariable:

修改后的控制器方法:

@GetMapping("/services/{id}")
public ResponseEntity<Service> getServiceById(@PathVariable Long id){
    try{
        Service service = serviceService.getById(id);
        return new ResponseEntity<>(service, HttpStatus.OK);
    }catch(NoSuchElementException e){
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}

核心问题2:类名与Java关键字冲突

Service是Java的关键字,这可能导致JPA在映射数据库表时出现未知问题,建议修改类名为非关键字,比如ServiceInfo:

@Entity
@Getter
@Setter
public class ServiceInfo {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private BigDecimal price;
}

同时同步修改ServiceRepo、ServiceService和控制器中的泛型及引用。

其他优化点

  1. 删除重复的Repository方法:JpaRepository已经自带findById(Long id)方法,不需要在ServiceRepo中重复定义,直接删除该方法即可:
public interface ServiceRepo extends JpaRepository<ServiceInfo, Long>, JpaSpecificationExecutor<ServiceInfo> {
    // 移除Optional<Service> findById(Long id);
}
  1. 优化Optional的处理:ServiceService中的getById方法直接调用.get()会在无数据时抛出NoSuchElementException,可以改用更清晰的方式:
public ServiceInfo getById(Long id) {
    return serviceRepo.findById(id)
            .orElseThrow(() -> new NoSuchElementException("Service not found with id: " + id));
}

验证步骤

  1. 启动应用后,访问/services确认数据正常加载。
  2. 访问/services/1(替换为实际存在的ID),检查是否能返回对应数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 10:42:26