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

Spring JPA ManyToOne关联findBy查询报错无法识别PlanEntity.id问题解决

报错根因

该报错的核心触发原因有两类:

  1. Spring Data JPA未识别到你定义的@Query注解,转而尝试根据findByPlan方法名自动生成查询逻辑:方法名findByPlan期望传入PlanEntity类型参数,你传入的是Long类型的planId,类型不匹配导致属性解析失败。
  2. PlanEntity的id属性没有公开的Getter方法,JPA依赖反射读取实体属性,私有属性如果没有对应getter会被判定为不存在该属性。
解决方案

按以下步骤逐一排查即可解决:

步骤1:补充实体类的Getter/Setter方法

确保PlanEntity和TagEntity的所有持久化属性都有public的get/set方法,如果你使用Lombok,直接给实体类添加@Data注解即可快速生成:

@Data // 也可以单独加@Getter/@Setter注解
@Entity
public class PlanEntity{
    @Id
    private Long id;

    @OneToMany(mappedBy="plan", cascade=CascadeType.ALL, orphanRemoval=true)
    private Set<TagEntity> tags;
    // 其他属性
}

@Data
@Entity
public class TagEntity{
    @Id
    private Long id;

    @ManyToOne
    @JoinColumn(name="plan_id", referencedColumnName="id")
    private PlanEntity plan;
    // 其他属性
}

步骤2:修正Repository的语法错误

你当前的Repository代码存在三处问题:@Query导包错误、JPQL返回类型和声明不匹配、in关键字使用不当。
首先确认@Query导入的是Spring Data JPA的官方包:

import org.springframework.data.jpa.repository.Query;

再根据你的业务需求修正查询逻辑:

需求1:根据planId查询关联的所有Tag

推荐直接使用JPA方法名派生查询,不需要手写JPQL,代码如下:

public interface TagEntityRepository extends JpaRepository<TagEntity, Long>{
    // 方法名自动映射查询逻辑:查询Tag中plan.id等于传入参数的所有记录
    List<TagEntity> findAllByPlan_Id(Long planId);
}

如果要手写JPQL,正确写法如下:

public interface TagEntityRepository extends JpaRepository<TagEntity, Long>{
    @Query("select t from TagEntity t where t.plan.id = :planId")
    List<TagEntity> findByPlanId(Long planId);
}

需求2:根据planId查询对应的Plan实体

直接在PlanEntity对应的Repository中调用内置的findById()方法即可,不需要在TagRepository中额外定义查询。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 16:24:04