The Price of all “Rest with Spring” course packages will increase by $50 next Friday:

>>> GET ACCESS NOW

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.

2. Maven Dependencies

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

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-couchbase</artifactId>
    <version>2.0.0.RELEASE</version>
</dependency>

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

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

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.2.4.Final</version>
</dependency>

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:

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.9.2</version>
</dependency>

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

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

@Configuration
@EnableCouchbaseRepositories(basePackages={"org.baeldung.spring.data.couchbase"})
public class MyCouchbaseConfig extends AbstractCouchbaseConfiguration {

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

    @Override
    protected String getBucketName() {
        return "baeldung";
    }

    @Override
    protected String getBucketPassword() {
        return "";
    }
}

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

@Override
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="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://www.springframework.org/schema/data/couchbase
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/couchbase
    http://www.springframework.org/schema/data/couchbase/spring-couchbase.xsd">

    <couchbase:cluster>
        <couchbase:node>localhost</couchbase:node>
    </couchbase:cluster>

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

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

    <couchbase:repositories base-package="org.baeldung.spring.data.couchbase"/>
</beans:beans>

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

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.

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:

@Document
public class Person {
    @Id
    private String id;
    
    @Field
    @NotNull
    private String firstName;
    
    @Field
    @NotNull
    private String lastName;
    
    @Field
    @NotNull
    private DateTime created;
    
    @Field
    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:

@Id
@Field
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:

@Field("fname")
private String firstName;

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

{
    "firstName": "John",
    "lastName": "Smith",
    "created": 1457193705667
    "_class": "org.baeldung.spring.data.couchbase.model.Person"
}

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.

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:

@Override
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:

@Override
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.

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

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:

CREATE PRIMARY INDEX ON baeldung USING GSI;

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 == "org.baeldung.spring.data.couchbase.model.Person") {
        emit(meta.id, 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:

@View
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 == "org.baeldung.spring.data.couchbase.model.Person"
      && 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:

@View("myCustomView")
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:

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:

@Service
@Qualifier("PersonRepositoryService")
public class PersonRepositoryService implements PersonService {
    
    @Autowired
    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()) {
            people.add(it.next());
        }
        return people;
    }

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

    public void create(Person person) {
        person.setCreated(DateTime.now());
        repo.save(person);
    }

    public void update(Person person) {
        person.setUpdated(DateTime.now());
        repo.save(person);
    }

    public void delete(Person person) {
        repo.delete(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:

@Service
@Qualifier("PersonTemplateService")
public class PersonTemplateService implements PersonService {
    private static final String DESIGN_DOC = "person";
    @Autowired
    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) {
        person.setCreated(DateTime.now());
        template.insert(person);
    }

    public void update(Person person) {
        person.setUpdated(DateTime.now());
        template.update(person);
    }

    public void delete(Person person) {
        template.remove(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.

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

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

The Price of all “Rest with Spring” course packages will increase by $50 next Friday:

>>> GET ACCESS NOW

Sort by:   newest | oldest | most voted
nuuj
Guest

the findByFirstName is not working for me, instead of returning only John, it is returning both john and foo:bar. The code is exactly the same as it is in github except that I added @View annotation on the findByFirstName(String firstName) method as I am using couchbase server 3.0.1.

Eugen Paraschiv
Guest

That’s interesting – let’s go with a PR that reproducing the issue (a failing test and the change you made) and I’ll look into it. Cheers,
Eugen.

nuuj
Guest

I have created the PR, infact it does not even work for me for couchbase 4.x version

wpDiscuz