How to fetch a field from document using n1ql with spring-data-couchbase

丶灬走出姿态 提交于 2019-12-02 07:27:21

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.

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}

which is equivalent (in pure N1QL) to:

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

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
}

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.

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).

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)...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!