如何通过@Query注解向Couchbase查询传递参数?我的实现返回null
问题分析与修复
你的代码里有两个关键错误导致查询返回null:
- 参数引用语法错误:你在反引号里多写了一个冒号
:,导致生成的N1QL语句中,字段名变成了:[传入的carId值](比如传入123的话就是:123),而你的文档里显然不存在带冒号的字段,自然查不到数据。 - SpEL表达式与参数占位符混用:你错误地把SpEL的
#{#carId}和多余的冒号放在一起,破坏了字段名的正确生成。
修复方案
直接去掉多余的冒号即可,以下是两种可行的写法:
写法一:使用SpEL表达式拼接字段名
@Repository public interface CarRepository extends CouchbaseRepository<CarDocument, String> { @Query( value = "#{#n1ql.selectEntity} #{#n1ql.bucket} where cars.`#{#carId}` is not missing;" ) List<CarDocument> getCarDocumentsByCarId(@Param("carId") Integer carId); }
写法二:使用命名参数占位符
@Repository public interface CarRepository extends CouchbaseRepository<CarDocument, String> { @Query( value = "#{#n1ql.selectEntity} #{#n1ql.bucket} where cars.`$carId` is not missing;" ) List<CarDocument> getCarDocumentsByCarId(@Param("carId") Integer carId); }
这两种写法都会正确生成目标字段名(比如传入123时,生成cars.123),从而匹配文档中存在对应字段的数据。
内容的提问来源于stack exchange,提问作者Emanuel
相关产品推荐
相关产品推荐

