跳到主要内容
版本:6.1.1

集合支持

Doubao 中英对照 Collection Support

Couchbase 支持作用域与集合。本节介绍如何在 Spring Data Couchbase 中使用它们。

try-cb-spring 示例应用程序是在 Spring Data Couchbase 中使用作用域与集合的一个可运行示例。

2021 年 Couchbase Connect 上关于 Spring Data 中集合的演示,可在仅演示和带幻灯片的演示中找到。

要求​

  • Couchbase Server 7.0 或更高版本。

  • Spring Data Couchbase 4.3.1 或更高版本。

入门与配置​

作用域与集合的指定​

指定作用域与集合有多种机制,它们可以组合使用,也可以一种机制覆盖另一种。首先说明作用域与集合的几个定义。未指定作用域表示使用默认作用域,同样,未指定集合表示使用默认集合。作用域与集合只有三种组合是有效的:(1) 默认作用域与默认集合;(2) 默认作用域与非默认集合;(3) 非默认作用域与非默认集合。不能使用非默认作用域与默认集合,因为非默认作用域不包含默认集合,也无法创建默认集合。

可以在配置中指定作用域:

@Configuration
static class Config extends AbstractCouchbaseConfiguration {

// Usual Setup
@Override public String getConnectionString() { /* ... */ }

// optionally specify the scope in the Configuration
@Override
protected String getScopeName() {
return "myScope"; // or a variable etc.;
}

}

作用域与集合可以作为注解指定在实体类和仓库上:

@Document
@Scope("travel")
@Collection("airport")
public class Airport {...
@Scope("travel")
@Collection("airport")
public interface AirportRepository extends CouchbaseRepository<Airport, String> ...

可以在模板上使用 inScope(scopeName) 和 inCollection(collectionName) 流式 API 指定作用域与集合:

List<Airport> airports = template.findByQuery(Airport.class).inScope("archived").all()

可以在扩展了 DynamicProxyable 的仓库上使用 withScope(scopeName) 和 withCollection(collectionName) API 指定作用域与集合:

public interface AirportRepository extends CouchbaseRepository<Airport, String>, DynamicProxyable<AirportRepository>{...}
...
List<Airport> airports = airportRepository.withScope("archived").findByName(iata);

优先级顺序如下:

  1. 模板流式 API 的 inScope()/inCollection()

  2. 模板/仓库对象的 withScope()/withCollection()

  3. 仓库方法的注解

  4. 仓库接口的注解

  5. 实体对象的注解

  6. 配置的 getScope()