【问题标题】:Not found in annotated query error with @Query在带有 @Query 的带注释的查询错误中找不到
【发布时间】:2026-01-19 18:50:02
【问题描述】:

我正在使用带有 REST 的 spring 数据。我有一个表 country 和一个与之对应的实体,称为 Country.java

我已将 CountryRepositopry 中的方法注释为

public interface CountryRepository extends Repository<Country, Short> {

    @RestResource(path = "bycode3")
        @Query("select c from Country c where c.codeAlpha3=?1 and c.active=1")
        Country findCountryByCodeAlpha3(@Param("code") String countryCode);
 }

我在启动 tomcat 时遇到以下异常-

Caused by: java.lang.IllegalStateException: Using named parameters for method public abstract com.persistence.entity.common.Country com.persistence.repository.CountryRepository.findCountryByCodeAlpha3(java.lang.String) but parameter 'code' not found in annotated query 'select c from Country c where c.codeAlpha3=?1 and c.active=1'!

【问题讨论】:

  • 使用:而不是?

标签: jpa spring-data-rest


【解决方案1】:

我搞定了

查询需要修改为

@Query("select c from Country c where c.codeAlpha3=:code and c.active=1") 

应该是 :code

而不是 ?1

【讨论】:

    【解决方案2】:

    @Param("xxx") 中的文本xxx 必须在查询value 中使用。

    【讨论】:

      【解决方案3】:

      如果你使用@Param注解,你应该使用与你的实体类参数相同的参数,并且在“(@Param("code") String countryCode)”中也使用相同的参数:

      public interface CountryRepository extends Repository<Country, Short> {
      
          @RestResource(path = "bycode3")
              @Query("select c from Country c where c.codeAlpha3=?1 and c.active=1")
              Country findCountryByCodeAlpha3(@Param("code") String countryCode);
       }
      

      按照这个,应该改成这样:

      @RestResource(path = "bycode3")
          @Query("select c from Country c where c.codeAlpha3=?1 and c.active=1")
          Country findCountryByCodeAlpha3(@Param("codeAlpha3") String countryCode);
      

      【讨论】:

        【解决方案4】:

        你可以试试这个,但是 始终确保@Param("code") 中的字符串值与您要在查询中使用的命名变量值相同。

        @RestResource(path = "bycode3")
            @Query("select c from Country where c.codeAlpha3=:code and c.active=1")
            Country findCountryByCodeAlpha3(@Param("code") String countryCode);
        

        【讨论】: