【问题标题】:Dealing with non-spring data documents in couchbase在 couchbase 中处理非弹簧数据文档
【发布时间】:2019-08-08 13:44:18
【问题描述】:

有没有推荐的方法来处理没有带有 spring-data-couchbase 的_class 字段的文档(如果有的话)?尝试它只是按预期抛出异常。

编辑:抱歉,如果这有点太模糊了,让我添加更多上下文。 我想按名字从沙发库中为某个学生获取数据,比如说。存储库看起来像 -

@Repository

公共接口 StudentRepository 扩展 CouchbaseRepository {

Optional<StudentDocument> findByName(String name);

}

现在 couchbase 中的文档没有 _class 字段,或者说我们是否为 _class 字段输入了不同的“键”和“值”,因为我们不想依赖它,所以这个方法失败了。我有点破解了这个使用的解决方法 -

`

@Override
public Student getStudent(String name) {
    N1qlQuery query = N1qlQuery.simple(String.format("select *, META().id AS _ID, META().cas AS _CAS" +
            " from student where name = \'%s\';", name));
    return Optional.ofNullable(studentRepository.getCouchbaseOperations()
            .findByN1QL(query, StudentWrapper.class)
            .get(0))
            .map(StudentWrapper::getStudent)
            .orElseGet(() -> {
                throw new HttpClientErrorException(HttpStatus.NOT_FOUND);
            });
}

`

我想知道是否有其他方法可以实现这一目标

【问题讨论】:

  • 交易是什么意思?理论上,您将始终使用您的 _class 过滤器,因此您不会得到任何不具有您指定类型的文档。
  • 嗯,一种情况是处理由使用 spring-boot 以外的框架的服务编写的遗留文档时。此外,将类的位置与使用 _class 字段反序列化的方式绑定到我看来有点奇怪(我知道由于 Spring Data 接口合同可能存在限制)。将它传递给我希望将其转换为的类型将是一个不错的选择 imo
  • 你不需要使用_class属性,你可以自己定义:stackoverflow.com/questions/55098306/…
  • 但这将帮助我为 json 中的键和值(用于 _class 字段)编写不同的值。但是当我试图从 couchbase 读取数据时,我无法弄清楚它是如何工作的。

标签: spring-data couchbase spring-data-couchbase


【解决方案1】:

在使用 Spring spEL 时,Couchbase 会自动为您包含 _class(或您定义为类型的任何属性):

public interface AreaRepository extends CouchbaseRepository<Area, String> {
   //The _class/type is automatically included by Couchbase 
    List<Area> findByBusinessUnityIdAndRemoved(String businessId, boolean removed);
}

但是,如果你想使用 N1QL,你必须添加 #{#n1ql.filter} :

public interface BusinessUnityRepository extends CouchbaseRepository<BusinessUnity, String>{

    @Query("#{#n1ql.selectEntity} where #{#n1ql.filter} and companyId = $2 and $1 within #{#n1ql.bucket}")
    BusinessUnity findByAreaRefId(String areaRefId, String companyId);

}

#{#n1ql.filter} 会自动为您添加过滤器类型。

【讨论】:

  • 嗨丹尼斯!我想我的问题有点不清楚。我已经更新了一点。如果我错了,请纠正我,但您在这里分享的方法是根据 _class 字段(或任何重命名的字段)选择文档?
  • 很抱歉。当您的文档中没有“_class”属性时,您的“hack”是加载文档的正确方法。我使用几乎相同的代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-28
  • 2012-07-03
  • 1970-01-01
  • 1970-01-01
  • 2013-08-23
  • 2019-05-03
  • 1970-01-01
相关资源
最近更新 更多