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>5.0.3</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.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>8.0.1.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.12.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 = { "com.baeldung.spring.data.couchbase" })
public class MyCouchbaseConfig extends AbstractCouchbaseConfiguration {

    public static final String NODE_LIST = "localhost";
    public static final String BUCKET_NAME = "baeldung";
    public static final String BUCKET_USERNAME = "baeldung";
    public static final String BUCKET_PASSWORD = "baeldung";

    @Override
    public String getConnectionString() {
        return NODE_LIST;
    }

    @Override
    public String getUserName() {
        return BUCKET_USERNAME;
    }

    @Override
    public String getPassword() {
        return BUCKET_PASSWORD;
    }

    @Override
    public String getBucketName() {
        return BUCKET_NAME;
    }

    @Override
    public QueryScanConsistency getDefaultConsistency() {
        return QueryScanConsistency.REQUEST_PLUS;
    }

    @Bean
    public LocalValidatorFactoryBean localValidatorFactoryBean() {
        return new LocalValidatorFactoryBean();
    }

    @Bean
    public ValidatingCouchbaseEventListener validatingCouchbaseEventListener() {
        return new ValidatingCouchbaseEventListener(localValidatorFactoryBean());
    }
}

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

@Override
protected CouchbaseEnvironment getEnvironment() {
   ...
}

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": "com.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);

    List<Person> findByLastName(String lastName);
}

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 == "com.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 == "com.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 {
    Optional<Person> findOne(String id);
    List<Person> findAll();
    List<Person> findByFirstName(String firstName);
    List<Person> findByLastName(String lastName);
    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 Optional<Person> findOne(String id) {
        return repo.findById(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

The CouchbaseTemplate object is available in our Spring context and may be injected into the service class. In spring data couchbase 5.0.3 removed the methods to find an document by a view. You can use findByQuery instead.

Here is the implementation using the template abstraction:

@Service
@Qualifier("PersonTemplateService")
public class PersonTemplateService implements PersonService {

    private static final String DESIGN_DOC = "person";

    private CouchbaseTemplate template;

    @Autowired
    public void setCouchbaseTemplate(CouchbaseTemplate template) {
        this.template = template;
    }

    public Optional<Person> findOne(String id) {
        return Optional.of(template.findById(Person.class).one(id));
    }

    public List<Person> findAll() {
        return template.findByQuery(Person.class).all();
    }

    public List<Person> findByFirstName(String firstName) {
        return template.findByQuery(Person.class).matching(where("firstName").is(firstName)).all();
    }

    public List<Person> findByLastName(String lastName) {
        return template.findByQuery(Person.class).matching(where("lastName").is(lastName)).all();
    }

    public void create(Person person) {
        person.setCreated(DateTime.now());
        template.insertById(Person.class).one(person);
    }

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

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

Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE
res – Persistence (eBook) (cat=Persistence)
Comments are closed on this article!