Integrating Couchbase with a Spring Boot application

To integrate Spring Boot with Couchbase for CRUD (Create, Read, Update, Delete) operations, follow this guide:


1. Setup Your Spring Boot Project

Add Dependencies

Add the required dependencies for Spring Boot and Couchbase in your pom.xml (if using Maven):

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-couchbase</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>


2. Configure Couchbase

Add Couchbase Configuration in application.properties or application.yml

Provide your Couchbase cluster details, bucket, and other configurations.

spring.couchbase.connection-string=couchbase://127.0.0.1
spring.couchbase.username=admin
spring.couchbase.password=password
spring.couchbase.bucket-name=my_bucket


Create a Custom Configuration Class

You can optionally create a custom configuration class if needed:

import org.springframework.context.annotation.Configuration;
import org.springframework.data.couchbase.config.AbstractCouchbaseConfiguration;

@Configuration
public class CouchbaseConfig extends AbstractCouchbaseConfiguration {

    @Override
    public String getConnectionString() {
        return "couchbase://127.0.0.1";
    }

    @Override
    public String getUserName() {
        return "admin";
    }

    @Override
    public String getPassword() {
        return "password";
    }

    @Override
    public String getBucketName() {
        return "my_bucket";
    }
}


3. Define a Model Class

Annotate the entity class with @Document for Couchbase.

import org.springframework.data.annotation.Id;
import org.springframework.data.couchbase.core.mapping.Document;

@Document
public class Employee {
    
    @Id
    private String id;
    private String name;
    private String department;

    // Getters and setters

    public Employee() {}

    public Employee(String id, String name, String department) {
        this.id = id;
        this.name = name;
        this.department = department;
    }

    // toString, equals, hashCode methods
}


4. Create a Repository

Spring Data Couchbase simplifies data access with the CrudRepository interface.

import org.springframework.data.couchbase.repository.CouchbaseRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EmployeeRepository extends CouchbaseRepository<Employee, String> {
    // Custom query methods (if needed)
    List<Employee> findByDepartment(String department);
}


5. Service Layer

Add a service to encapsulate the business logic.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;

@Service
public class EmployeeService {

    @Autowired
    private EmployeeRepository repository;

    public Employee saveEmployee(Employee employee) {
        return repository.save(employee);
    }

    public Optional<Employee> getEmployeeById(String id) {
        return repository.findById(id);
    }

    public List<Employee> getAllEmployees() {
        return repository.findAll();
    }

    public void deleteEmployee(String id) {
        repository.deleteById(id);
    }
}


6. Controller Layer

Expose REST APIs for CRUD operations.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

    @Autowired
    private EmployeeService service;

    @PostMapping
    public Employee createEmployee(@RequestBody Employee employee) {
        return service.saveEmployee(employee);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Employee> getEmployeeById(@PathVariable String id) {
        return service.getEmployeeById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping
    public List<Employee> getAllEmployees() {
        return service.getAllEmployees();
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteEmployee(@PathVariable String id) {
        service.deleteEmployee(id);
        return ResponseEntity.noContent().build();
    }
}


7. Run and Test the Application

  • Start your Couchbase server and create the bucket defined in the configuration.
  • Run your Spring Boot application.
  • Test the CRUD operations using tools like Postman, cURL, or a frontend client.

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example