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

Spring JPA多参数@Query查询报错:找不到Optional[goingTo]参数

Spring JPA多参数查询报错解决方案

你的查询代码:

@Query("FROM Flight f WHERE f.goingTo.city =: goingTo and f.leavingFrom.city = :leavingFrom")
List<Flight> findByGoingToAndLeavingFrom(String goingTo,String leavingFrom);

执行时出现的错误:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'flightManager' defined in file [C:\Users\msi\Desktop\spring\flight-search-api\flight-search-api\target\classes\com\example\flightsearchapi\service\impl\FlightManager.class]: Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'flightRepository' defined in com.example.flightsearchapi.repository.FlightRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Could not create query for public abstract java.util.List com.example.flightsearchapi.repository.FlightRepository.aaa(java.lang.String,java.lang.String); Reason: Using named parameters for method public abstract java.util.List com.example.flightsearchapi.repository.FlightRepository.aaa(java.lang.String,java.lang.String) but parameter 'Optional[goingTo]' not found in annotated query 'FROM Flight f WHERE f.goingTo.city =: goingTo and f.leavingFrom.city = :leavingFrom'

问题原因

报错核心是命名参数的冒号与参数名之间存在多余空格:第一个参数=: goingTo里冒号后有空格,导致Spring无法正确识别参数名goingTo,进而提示找不到该参数。单个参数时Spring可能通过位置匹配机制正常工作,但多参数场景下必须严格遵循命名参数的格式规范。

修复方案

方案1:修正参数格式,去掉冒号后的空格

@Query("FROM Flight f WHERE f.goingTo.city = :goingTo and f.leavingFrom.city = :leavingFrom")
List<Flight> findByGoingToAndLeavingFrom(String goingTo, String leavingFrom);

方案2:使用@Param注解明确绑定参数名(推荐,增强代码可读性)

import org.springframework.data.repository.query.Param;

@Query("FROM Flight f WHERE f.goingTo.city = :goingTo and f.leavingFrom.city = :leavingFrom")
List<Flight> findByGoingToAndLeavingFrom(@Param("goingTo") String goingTo, @Param("leavingFrom") String leavingFrom);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 01:57:27