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

Spring Boot中JPA自带findById方法无法找到存在的数据库对象

Spring Boot JPA findById方法返回空对象问题排查与解决

问题描述

在Spring Boot应用中执行数据库记录更新操作时,调用JPA查询方法findById(Integer id)根据ID查找对象,返回结果始终为空,但仓库接口中的其他查询方法(如findAll(Pageable pageable))均能正常工作。

相关代码片段

仓库接口

@Repository
public interface ProductsRepository extends PagingAndSortingRepository<Products, Integer> {

    Page<Products> findAll(Pageable pageable);

    void save(Products product);

    Optional<Products> findById(Integer id);

    // ...
}

服务层调用代码

//...
Optional<Products> oldProduct = productsRepository.findById(productDto.getId());

if (oldProduct.isEmpty()){
    return ResponseEntity.badRequest().body("Product with id: "+productDto.getId()+" not found.");
}
//...

传入的ProductDTO JSON数据

{
    "id" : 1,
    "name" : "Taralli al peperoncino",
    "price" : 3.6,
    "quantity" : 15,
    "availableFrom" : "10/04/2023 00:00:00",
    "availableUntil" : "13/07/2023 00:00:00",
    "categoryId" : "8",
    "imageBase64" : ""
}

尝试的解决方案

为排查问题,尝试用原生SQL重写查询方法,该方法能够正常工作:

@Query(value = "SELECT * FROM eshop_products where id=:id", nativeQuery = true)
Optional<Products> findById(Integer id);

已解决情况

目前findById方法已恢复正常,推测问题根源为缓存导致。仅添加了配置spring.jpa.show-sql=true后,JPA原生查询方法就恢复了正常工作。

技术栈

  • Spring v3.0
  • Java v17
  • JPA最新版(2023年6月7日)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 19:40:01