Intro to Spring Data Couchbase – Spring Data Couchbase介绍

最后修改: 2016年 3月 13日


1. Introduction


In this tutorial on Spring Data, we’ll discuss how to set up a persistence layer for Couchbase documents using both the Spring Data repository and template abstractions, as well as the steps required to prepare Couchbase to support these abstractions using views and/or indexes.

在这个关于Spring Data的教程中,我们将讨论如何使用Spring Data资源库和模板抽象为Couchbase文档建立一个持久层,以及准备Couchbase使用视图和/或索引支持这些抽象所需的步骤。

2. Maven Dependencies


First, we add the following Maven dependency to our pom.xml file:



Note that by including this dependency, we automatically get a compatible version of the native Couchbase SDK, so we need not include it explicitly.

请注意,通过包含这个依赖关系,我们会自动得到一个兼容的本地Couchbase SDK版本,所以我们不需要明确地包含它。

To add support for JSR-303 bean validation, we also include the following dependency:

为了增加对JSR-303 Bean验证的支持,我们还包括以下依赖关系。


Spring Data Couchbase supports date and time persistence via the traditional Date and Calendar classes, as well as via the Joda Time library, which we include as follows:

Spring Data Couchbase通过传统的Date和Calendar类以及Joda Time库来支持日期和时间的持久性,我们将其包含在下面。


3. Configuration


Next, we’ll need to configure the Couchbase environment by specifying one or more nodes of our Couchbase cluster and the name and password of the bucket in which we will store our documents.


3.1. Java Configuration

3.1. Java配置

For Java class configuration, we simply extend the AbstractCouchbaseConfiguration class:


public class MyCouchbaseConfig extends AbstractCouchbaseConfiguration {

    protected List<String> getBootstrapHosts() {
        return Arrays.asList("localhost");

    protected String getBucketName() {
        return "baeldung";

    protected String getBucketPassword() {
        return "";

If your project requires more customization of the Couchbase environment, you may provide one by overriding the getEnvironment() method:


protected CouchbaseEnvironment getEnvironment() {

3.2. XML Configuration


Here is the equivalent configuration in XML:


<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans=""


    <couchbase:clusterInfo login="baeldung" password="" />

    <couchbase:bucket bucketName="baeldung" bucketPassword=""/>

    <couchbase:repositories base-package=""/>

Note: the “clusterInfo” node accepts either cluster credentials or bucket credentials and is required so that the library can determine whether or not your Couchbase cluster supports N1QL (a superset of SQL for NoSQL databases, available in Couchbase 4.0 and later).

注意:”clusterInfo“节点接受集群凭证或桶凭证,并且是必须的,以便库可以确定你的Couchbase集群是否支持N1QL(NoSQL数据库的SQL超集,在Couchbase 4.0及以后版本中可用)。

If your project requires a custom Couchbase environment, you may provide one using the <couchbase:env/> tag.


4. Data Model


Let’s create an entity class representing the JSON document to persist. We first annotate the class with @Document, and then we annotate a String field with @Id to represent the Couchbase document key.


You may use either the @Id annotation from Spring Data or the one from the native Couchbase SDK. Be advised that if you use both @Id annotations in the same class on two different fields, then the field annotated with the Spring Data @Id annotation will take precedence and will be used as the document key.

你可以使用Spring Data的@Id注解,或者使用本地Couchbase SDK的注解。请注意,如果你在同一个类中对两个不同的字段同时使用@Id注解,那么用Spring Data的@Id注解的字段将被优先使用,并将被用作文档键。

To represent the JSON documents’ attributes, we add private member variables annotated with @Field. We use the @NotNull annotation to mark certain fields as required:


public class Person {
    private String id;
    private String firstName;
    private String lastName;
    private DateTime created;
    private DateTime updated;
    // standard getters and setters

Note that the property annotated with @Id merely represents the document key and is not necessarily part of the stored JSON document unless it is also annotated with @Field as in:


private String id;

If you want to name a field in the entity class differently from what is to be stored in the JSON document, simply qualify its @Field annotation, as in this example:


private String firstName;

Here is an example showing how a persisted Person document would look:


    "firstName": "John",
    "lastName": "Smith",
    "created": 1457193705667
    "_class": ""

Notice that Spring Data automatically adds to each document an attribute containing the full class name of the entity. By default, this attribute is named “_class”, although you can override that in your Couchbase configuration class by overriding the typeKey() method.

请注意,Spring Data会自动给每个文档添加一个包含实体全类名称的属性。默认情况下,这个属性被命名为“_class”,尽管你可以通过覆盖typeKey()方法在你的Couchbase配置类中覆盖它。

For example, if you want to designate a field named “dataType” to hold the class names, you would add this to your Couchbase configuration class:


public String typeKey() {
    return "dataType";

Another popular reason to override typeKey() is if you are using a version of Couchbase Mobile that does not support fields prefixed with the underscore. In this case, you can choose your own alternate type field as in the previous example, or you can use an alternate provided by Spring:

覆盖typeKey()的另一个流行原因是,如果你使用的Couchbase Mobile版本不支持以下划线为前缀的字段。在这种情况下,你可以像前面的例子一样选择你自己的替代类型字段,或者你可以使用Spring提供的替代类型。

public String typeKey() {
    // use "javaClass" instead of "_class"
    return MappingCouchbaseConverter.TYPEKEY_SYNCGATEWAY_COMPATIBLE;

5. Couchbase Repository


Spring Data Couchbase provides the same built-in queries and derived query mechanisms as other Spring Data modules such as JPA.

Spring Data Couchbase提供了与其他Spring Data模块(如JPA)一样的内置查询和派生查询机制。

We declare a repository interface for the Person class by extending CrudRepository<String,Person> and adding a derivable query method:


public interface PersonRepository extends CrudRepository<Person, String> {
    List<Person> findByFirstName(String firstName);

6. N1QL Support via Indexes


If using Couchbase 4.0 or later, then by default, custom queries are processed using the N1QL engine (unless their corresponding repository methods are annotated with @View to indicate the use of backing views as described in the next section).

如果使用Couchbase 4.0或更高版本,那么默认情况下,自定义查询是使用N1QL引擎来处理的(除非其对应的存储库方法被注释为@View以表示使用支持视图,如下一节所述)。

To add support for N1QL, you must create a primary index on the bucket. You may create the index by using the cbq command-line query processor (see your Couchbase documentation on how to launch the cbq tool for your environment) and issuing the following command:



In the above command, GSI stands for global secondary index, which is a type of index particularly suited for optimization of ad hoc N1QL queries in support of OLTP systems and is the default index type if not otherwise specified.


Unlike view-based indexes, GSI indexes are not automatically replicated across all index nodes in a cluster, so if your cluster contains more than one index node, you will need to create each GSI index on each node in the cluster, and you must provide a different index name on each node.


You may also create one or more secondary indexes. When you do, Couchbase will use them as needed in order to optimize its query processing.


For example, to add an index on the firstName field, issue the following command in the cbq tool:


CREATE INDEX idx_firstName ON baeldung(firstName) USING GSI;

7. Backing Views


For each repository interface, you will need to create a Couchbase design document and one or more views in the target bucket. The design document name must be the lowerCamelCase version of the entity class name (e.g. “person”).


Regardless of which version of Couchbase Server you are running, you must create a backing view named “all” to support the built-in “findAll” repository method. Here is the map function for the “all” view for our Person class:


function (doc, meta) {
    if(doc._class == "") {
        emit(, null);

Custom repository methods must each have a backing view when using a Couchbase version prior to 4.0 (the use of backing views is optional in 4.0 or later).


View-backed custom methods must be annotated with @View as in the following example:


List<Person> findByFirstName(String firstName);

The default naming convention for backing views is to use the lowerCamelCase version of that part of the method name following the “find” keyword (e.g. “byFirstName”).


Here is how you would write the map function for the “byFirstName” view:


function (doc, meta) {
    if(doc._class == ""
      && doc.firstName) {
        emit(doc.firstName, null);

You can override this naming convention and use your own view names by qualifying each @View annotation with the name of your corresponding backing view. For example:


List<Person> findByFirstName(String lastName);

8. Service Layer


For our service layer, we define an interface and two implementations: one using the Spring Data repository abstraction, and another using the Spring Data template abstraction. Here is our PersonService interface:

对于我们的服务层,我们定义了一个接口和两个实现:一个使用Spring Data资源库抽象,另一个使用Spring Data模板抽象。下面是我们的PersonService接口。

public interface PersonService {
    Person findOne(String id);
    List<Person> findAll();
    List<Person> findByFirstName(String firstName);
    void create(Person person);
    void update(Person person);
    void delete(Person person);

8.1. Repository Service


Here is an implementation using the repository we defined above:


public class PersonRepositoryService implements PersonService {
    private PersonRepository repo; 

    public Person findOne(String id) {
        return repo.findOne(id);

    public List<Person> findAll() {
        List<Person> people = new ArrayList<Person>();
        Iterator<Person> it = repo.findAll().iterator();
        while(it.hasNext()) {
        return people;

    public List<Person> findByFirstName(String firstName) {
        return repo.findByFirstName(firstName);

    public void create(Person person) {

    public void update(Person person) {

    public void delete(Person person) {

8.2. Template Service


For the template-based implementation, we must create the backing views listed in section 7 above. The CouchbaseTemplate object is available in our Spring context and may be injected into the service class.


Here is the implementation using the template abstraction:


public class PersonTemplateService implements PersonService {
    private static final String DESIGN_DOC = "person";
    private CouchbaseTemplate template;
    public Person findOne(String id) {
       return template.findById(id, Person.class);

    public List<Person> findAll() {
        return template.findByView(ViewQuery.from(DESIGN_DOC, "all"), Person.class);

    public List<Person> findByFirstName(String firstName) {
        return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName"), Person.class);

    public void create(Person person) {

    public void update(Person person) {

    public void delete(Person person) {

9. Conclusion


We have shown how to configure a project to use the Spring Data Couchbase module and how to write a simple entity class and its repository interface. We wrote a simple service interface and provided one implementation using the repository and another implementation using the Spring Data template API.

我们已经展示了如何配置一个项目来使用Spring Data Couchbase模块,以及如何编写一个简单的实体类及其存储库接口。我们写了一个简单的服务接口,并提供了一个使用存储库的实现和另一个使用Spring Data模板API的实现。

You can view the complete source code for this tutorial in the GitHub project.


For further information, visit the Spring Data Couchbase project site.

欲了解更多信息,请访问Spring Data Couchbase项目网站。