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
相关产品推荐
相关产品推荐

