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

如何通过@Query注解向Couchbase查询传递参数?我的实现返回null

问题分析与修复

你的代码里有两个关键错误导致查询返回null:

  1. 参数引用语法错误:你在反引号里多写了一个冒号:,导致生成的N1QL语句中,字段名变成了:[传入的carId值](比如传入123的话就是:123),而你的文档里显然不存在带冒号的字段,自然查不到数据。
  2. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 18:22:40