Spring Boot Application with Couchbase

Welcome, in this tutorial, we will see how to configure a spring boot application to use the couchbase bucket for storing information using spring data.

1. Introduction

Before going further in this tutorial, we will look at the common terminology such as introduction to Spring Boot, Couchbase db, and Lombok.

1.1 Spring Boot

1.2 Couchbase db

1.3 Lombok

1.3.1 Lombok features

Feature Details
val Local variables are declared as final
var Mutable local variables
@Slf4J Creates an SLF4J logger
@Cleanup Will call close() on the resource in the finally block
@Getter Creates getter methods for all properties
@Setter Creates setter for all non-final properties
  • Generates implementations of equals(Object other) and hashCode()
  • By default will use all non-static, non-transient properties
  • Can optionally exclude specific properties
  • Generates String of class name, and each field separated by commas
  • Optional parameter to include field names
  • Optional parameter to include a call to the super toString method
  • Generates no-args constructor
  • Will cause compiler error if there are final fields
  • Can optionally force, which will initialize final fields with 0/false/null var – mutable local variables
  • Generates a constructor for all fields that are final or marked @NonNull
  • The constructor will throw a NullPointerException if any @NonNull fields are null val – local variables are declared final
  • Generates a constructor for all properties of the class
  • Any @NotNull properties will have null checks
  • Generates typical boilerplate code for POJOs
  • Combines – @Getter, @Setter, @ToString, @EqualsAndHashCode, @RequiredArgsConstructor
  • No constructor is generated if constructors have been explicitly declared
  • Implements the Builder pattern for object creation
  • The immutable variant of @Data
  • All fields are made private and final by default

Let us go ahead with the tutorial implementation but before going any further I’m assuming that you’re aware of the Spring boot basics.

2. Spring Boot Application with Couchbase

2.1 Application Pre-requisite

To start with this tutorial, I am hoping you have the couchbase up and running in your localhost environment. For easy setup, I have the couchbase up and running on the Docker environment. You can execute the below script using the docker-compose command to get the couchbase container running on Docker in minutes. If you’re doing it for the first time the docker image will be downloaded from the docker hub.


    container_name: couchbase
    image: couchbase
      - '8091:8091'
      - '8092:8092'
      - '8093:8093'
      - '8094:8094'
      - '11210:11210'
version: '3.7'

If everything goes well the couchbase server container would be started successfully as shown in Fig. 1. You can use the docker ps -a command to confirm that the container is started successfully. For further information on docker basics, you can navigate to this tutorial.

Fig. 1: Couchbase server container on Docker

2.2 Tools Used for Spring boot application and Project Structure

We are using Eclipse Kepler SR2, JDK 8, and Maven. In case you’re confused about where you should create the corresponding files or folder, let us review the project structure of the spring boot application.

Fig. 2: Project structure

Let us start building the application!

3. Setup Couchbase Server and Create a table

Once the couchbase server is up and running, head over to the administration console by typing the following address in the browser – http://localhost:8901/. The administration console will open as shown in Fig. 3.

Fig. 3: Couchbase server welcome page

Click on the Setup New Cluster button to set up the new cluster details for the couchbase server as shown in Fig. 4. Use any password of your choice but remember it as this same password will be used to access the couchbase server via the console.

Fig. 4: Enter the new cluster details

Once done click on the Next button to accept the terms. On the terms page, you will have an option to either finish with defaults or configure disk, memory, and services. In this tutorial, we will do a custom setup.

Fig. 5: Accepting the couchbase server terms

Uncheck the Analytics and Eventing checkboxes and click Save & Finish as shown in Fig. 6.

Fig. 6: Configuring couchbase server

Once done, you will be successfully logged in to the couchbase server. The first thing here is to set up a bucket for storing information. Click on the Buckets in the right navigation bar and go to the Add Bucket button. Add the details as shown in Fig. 7 and click the Add Bucket button.

Fig. 7: Creating a new bucket

Once the bucket is successfully created we will need a user that can perform operations on the created bucket and this will the same user will be used in the spring boot application. Click on the Security in the right navigation bar and go to the Add User button. Add the details as shown in Fig. 8 and click the Add User button. Remember to keep the username as the bucket name and use the password of your choice but remember it as this same password will be used in the spring boot application.

Fig. 8: Add new user

4. Creating a Spring Boot application

Below are the steps involved in developing the application.

4.1 Maven Dependency

Here, we specify the dependency for the Spring boot (Web and Couchbase), Java Faker, and Lombok. The updated file will have the following code.


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <relativePath/> <!-- lookup parent from repository -->
    <description>Springboot and couchbase tutorial</description>
        <!-- java-faker -->

4.2 Application yml file

Create a new yml file at the location: Springbootandcouchbase/src/main/resources/ and add the following code to it. Here we will define the application and couchbase server configuration. Remember to enter the couchbase details that were used while setting up the couchbase server.


    org.springframework.data.couchbase.repository.query: DEBUG
  port: 9300
    name: springboot-couchbase
    bootstrap-hosts: ""
      name: jcgassignment
      password: password_1
      auto-index: true

4.3 Java Classes

Let us write the important java class(es) involved in this application. For brevity, we will skip the following classes –

4.3.1 Implementation/Main class

Add the following code to the main class to bootstrap the application from the main method. Always remember, the entry point of the spring boot application is the class containing @SpringBootApplication annotation and the static main method.


package com.springboot.couchbase;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import lombok.extern.slf4j.Slf4j;
//lombok annotation
//spring annotation
public class SpringbootandcouchbaseApplication {
	public static void main(String[] args) {
		SpringApplication.run(SpringbootandcouchbaseApplication.class, args);
		log.info("springboot and couchbase application started successfully");

4.3.2 Entity class

Add the following code to the entity class and the class will be annotated with the @Document annotation.


package com.springboot.couchbase.entity;
import com.couchbase.client.java.repository.annotation.Field;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.couchbase.core.mapping.Document;
import org.springframework.data.couchbase.core.mapping.id.GeneratedValue;
import org.springframework.data.couchbase.core.mapping.id.GenerationStrategy;
//lombok annotations
// identified the domain object to be persisted to couchbase
public class Employee {
    //identifies a field which will not be stored in the couchbase document but rather
    //used an document id
    @GeneratedValue(strategy = GenerationStrategy.UNIQUE)
    String id;
    //denotes a field which in the couchbase document
    @Field(value = "full_name")
    String fullName;
    int age;
    @Field(value = "phone_number")
    String phoneNumber;
    String address;
    @Field(value = "work_department")
    String workDepartment;

4.3.3 Repository interface

Add the following code to the repository interface to define the SQL CRUD functionality. The interface will be annotated with the couchbase server and the spring framework stereotype annotations.


package com.springboot.couchbase.repository;
import java.util.List;
import org.springframework.data.couchbase.core.query.N1qlPrimaryIndexed;
import org.springframework.data.couchbase.core.query.ViewIndexed;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.springboot.couchbase.entity.Employee;
//couchbase annotations
@ViewIndexed(designDoc = "employee")
//spring annotation
public interface EmployeeRepository extends CrudRepository<Employee, String> {
	List<Employee> findAllByWorkDepartment(String workDepartment);

4.3.4 Controller class

Add the following code to the controller class. The class is injected with the service dependency whose method will call the DAO layer methods to fetch the data from the couchbase bucket (named – jcgassignment).


package com.springboot.couchbase.controller;
import com.springboot.couchbase.entity.Employee;
import com.springboot.couchbase.exception.EntityNotFound;
import com.springboot.couchbase.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
//lombok annotation
//spring annotations
public class EmployeeController {
    EmployeeService service;
    //URL - http://localhost:9300/api/employees
    public List<Employee> getEmployees() {
        log.info("returning all employees from the couchbase");
        return service.getEmployees();
    //URL - http://localhost:9300/api/employee/<eid>
    //Example - http://localhost:9300/api/employee/73a02968-70a8-426a-b6d8-deaa96a597df
    public Employee getEmployeeById(@PathVariable String eid)
            throws EntityNotFound {
        log.info("returning employee id = {} from the couchbase", eid);
        return service.getEmployee(eid);
    //URL - http://localhost:9300/api/employee/<work_department>
    //Example - http://localhost:9300/api/employees/Health
    public List<Employee> getEmployeeByWorkDepartment(@PathVariable(name = "work_department") String workDepartment) {
        log.info("returning employees from couchbase where work-department = {}", workDepartment);
        return service.getEmployeesByWorkDepartment(workDepartment);
    //URL - http://localhost:9300/api/employees/count
    public long getTotalEmployees() {
        log.info("returning employees count from the couchbase");
        return service.count();

5. Run the Application

To execute the application, right-click on the Springbootandcouchbase.java class, Run As -> Java Application.

Fig. 9: Run the Application

6. Project Demo

When the application is started, open the Postman tool to hit the application endpoints to fetch the data from the couchbase bucket. You are free to use any other tool of your choice to make the get requests to the endpoints.

Application endpoints

-- HTTP GET endpoint (to fetch all the employees) –
-- HTTP GET endpoint (to fetch all employees by work department) --
-- HTTP GET endpoint (to fetch employee by id) --
-- HTTP GET endpoint (to fetch employees count) --

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

7. Summary

In this section, you learned,

You can download the sample application as an Eclipse project in the Downloads section.

8. Download the Project

This was an example of configuring the couchbase server in a spring boot application.

You can download the full source code of this example here: Spring Boot Application with Couchbase
Exit mobile version