【问题标题】:Using IN clause in couchbase N1Ql @query or use findAll(keys) from couchbase JPA在 couchbase N1Ql @query 中使用 IN 子句或使用 couchbase JPA 中的 findAll(keys)
【发布时间】:2018-03-23 12:13:05
【问题描述】:

我正在使用 Spring couchbase JPA 并尝试通过提供键列表来获取文档。我的存储库结构类似于

    public interface EmployeeRepo
    extends CouchbasePagingAndSortingRepository<Employee, String>, EmployeeCustomRepo {   

我有一个员工 ID 列表,可以搜索并获取相应的文档。我尝试使用 curdRepository 中的方法

    public List<Employee> findAllById(List<String> empIds) {
        return employeeRepo.findAll(empIds);
    }

但我得到异常::

org.springframework.dao.InvalidDataAccessResourceUsageException: 
View employee/all does not exist.; nested exception is 
com.couchbase.client.java.error.ViewDoesNotExistException: View 
employee/all does not exist.

即使我也尝试将我的键列表包装到一个 Iterable 对象。但例外情况保持不变。

    public List<Employee> findAllById(List<String> empIds) {
        Iterable<String> itrKeys = empIds;
        return employeeRepo.findAll(itrKeys);
    }

此外,我尝试使用 N1QL 和 @query over 方法

      @Query("#{#n1ql.selectEntity} WHERE meta().id IN $ids AND #{#n1ql.filter}")
Collection<ProductCopy> findAllById(@Param("ids") JsonArray ids);

我将我的键列表转换为 JsonArray。 以上 findAllById() 方法不会抛出任何异常,但即使我有匹配的键也不给出任何文档。

      @Query("#{#n1ql.selectEntity} USE KEYS ($ids) ")
Collection<ProductCopy> findByIdIn(@Param("ids") JsonArray ids);

在执行 findByIdIn() 时,我得到了这个异常 n1ql 错误:{"msg":"主键缺失或无效。

我的问题是为什么 findAll(Iterable id)/findAll(List id) 不工作,当 findOne(String id) 工作顺利时,我如何创建一个参数化的 N1QL 查询,它可以在 IN 语句中获取多个项目?

【问题讨论】:

    标签: java couchbase n1ql spring-data-couchbase


    【解决方案1】:

    尝试同时添加@N1qlPrimaryIndexed 和@ViewIndexed 注释,如下例所示:

    @N1qlPrimaryIndexed
    @ViewIndexed(designDoc = "businessUnity")
    public interface BusinessUnityRepository extends CouchbaseRepository<BusinessUnity, String>{
    
    List<BusinessUnity> findByCompanyId(String companyId);
    
    }
    

    此外,您还可以查看本教程:

    https://blog.couchbase.com/couchbase-spring-boot-spring-data/

    【讨论】:

    • 非常感谢@deniswsrosa。它工作顺利。能否请您解释一下它到底做了什么。
    • N1qlPrimaryIndexed 确保与当前存储库关联的存储桶将具有 N1QL 主索引。 ViewIndexed 为该实体生成一个视图以避免扫描整个存储桶
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多