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

Spring Boot中JPA findAll抛出EntityNotFoundException而非空列表

Spring Boot一对多关联查询抛出EntityNotFoundException异常

问题详情

在Spring Boot项目中,存在一对多关联的RoleForecasting和Opportunity实体类,调用roleForecastingRepository.findAll()方法时,未返回预期的RoleForecasting记录列表或空列表,反而抛出以下异常:

javax.persistence.EntityNotFoundException: Unable to find com.integrella.zoho.domain.Opportunity with id ABC132

补充说明:ID为ABC132的Opportunity确实存在于数据库中,且RoleForecasting表的外键也正确指向该ID。

实体类及Repository代码

RoleForecasting.java

@Getter
@Setter
@ToString(exclude = "opportunity")
@Entity
@Table(name = "RoleForecasting")
public class RoleForecasting extends AbstractAuditingEntity {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "`Id`")
  @Schema(example = "1")
  private Long id;

  ...

  @ManyToOne
  @JsonIgnore
  private Opportunity opportunity;

}

Opportunity.java

@Getter
@Setter
@ToString
@Entity
@Table(name = "Opportunity")
public class Opportunity extends AbstractAuditingEntity {

  @Id
  @Column(name = "`Id`")
  private String id;

  ...

  @OneToMany(mappedBy = "opportunity", cascade = CascadeType.ALL)
  private List<RoleForecasting> roleForecastings;

}

RoleForecastingRepository.java

@Repository
public interface RoleForecastingRepository extends JpaRepository<RoleForecasting, Long> {

}

解决方案

  • 显式指定关联外键列:给RoleForecasting的opportunity字段添加@JoinColumn注解,明确指定数据库中的外键列名,避免默认映射的列名与实际不符:
    @ManyToOne
    @JsonIgnore
    @JoinColumn(name = "opportunity_id") // 替换为数据库实际的外键列名
    private Opportunity opportunity;
    
  • 检查ID大小写匹配:如果使用的是区分大小写的数据库(如PostgreSQL),确认Opportunity表中存储的ABC132是精确的大小写格式,避免因大小写差异导致查询不到实体。
  • 禁用查询缓存:若开启了Hibernate二级缓存,可能存在缓存脏数据,可在Repository的findAll方法上添加注解禁用缓存:
    @Repository
    public interface RoleForecastingRepository extends JpaRepository<RoleForecasting, Long> {
        @QueryHints(value = @QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "false"))
        @Override
        List<RoleForecasting> findAll();
    }
    
  • 确保事务上下文有效:调用findAll()时需处于有效事务范围内,避免因会话提前关闭导致关联实体无法加载。
  • 修正ID字段映射:检查Opportunity的@Column注解,确保列名与数据库实际列名一致,可去掉不必要的反引号(若数据库不要求特殊标识符):
    @Id
    @Column(name = "Id")
    private String id;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 05:04:58