如何使用带有spring-data-couchbase的n1ql从文档中获取字段 [英] How to fetch a field from document using n1ql with spring-data-couchbase

查看:130
本文介绍了如何使用带有spring-data-couchbase的n1ql从文档中获取字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是存储库中的查询,可以正常工作.

This is the query in the repository which works fine.

public interface PlayerRepo extends CrudRepository<Player, String>{

@Query("#{#n1ql.selectEntity} WHERE code = $1 and #{#n1ql.filter}")
public List<Player> findPlayersWithCode(String code);
}

我想从Player文档中获取特定字段,如下所示:

I want to fetch specific field from Player document, like this:

@Query("#{#n1ql.selectEntity.name} WHERE code = $1 and #{#n1ql.filter}")
public List<String> findPlayerNamesWithCode(String code);

有可能做到这一点吗,我使用的是spring-data-couchbase 2.1.2

Is it possible to do this, I am using spring-data-couchbase 2.1.2

推荐答案

当前,这在存储库中是不可能的. Spring Data Hopper引入了允许使用的Projection功能,但是Couchbase存储实现尚未涵盖它.

Currently, this is not possible from a repository. Spring Data Hopper introduced a Projection feature that would allow it, but the Couchbase store implementation doesn't yet cover it.

CouchbaseTemplate中有一个很接近的东西,它具有一个findByN1QLProjection方法,但是它需要专用于该查询的DTO.例如:

There's something close in the CouchbaseTemplate, which has a findByN1QLProjection method, but it needs a DTO dedicated to the query. For example:

SELECT name, lastName FROM #{#n1ql.bucket} WHERE code = $1 AND #{#n1ql.filter}

(在纯N1QL中)等效于:

which is equivalent (in pure N1QL) to:

SELECT name, lastName FROM bucketThatBacksRepository WHERE code = $1 AND _class = "com.example.Person"

将需要以下类与findByN1QLProjection一起使用:

would require the following class to work with findByN1QLProjection:

public class PersonNameDTO {
    private final String name;
    private final String lastName;

    //constructor and maybe getters/setters needed but omitted here
}

它会产生一个List<PersonNameDTO>.请注意,除了它是围绕接口而不是具体的DTO类设计的以外,这与我在谈论的投影功能没有太大的不同.

And it would produce a List<PersonNameDTO>. Note that this is not hugely different from the projection feature I was talking about, except it's designed around interfaces rather than concrete DTO classes.

请注意,您不应使用#{#n1ql.selectEntity} SpEL,因为它的目的是要有一个较大的SELECT子句来覆盖给定实体的所有字段(而此处您要限制SELECT子句).

Note that you shouldn't use the #{#n1ql.selectEntity} SpEL since its purpose is to have a large SELECT clause that covers all the fields of a given entity (whereas here you want to restrict the SELECT clause).

它还覆盖了与存储库相关联的正确存储区的FROM部分,但是#{#n1ql.bucket}也包括了该部分(仅该部分)...

It also covers the FROM part with the correct bucket associated to your repository, but the #{#n1ql.bucket} also covers that part (and that part only)...

这篇关于如何使用带有spring-data-couchbase的n1ql从文档中获取字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆