First steps to build Spring Boot Application with Couchbase

Reading Time: 2 minutes

As the name of the blog suggests, we will be taking the first steps to build a simple application from scratch using Couchbase as a database and spring -boot as a framework. Let’s get started.

You can create a starter maven project using this link.
Add Web, Lombok and Couchbase dependencies. The pom.xml should look like:

Let’s run the spring boot application:

  1. How to download and run Couchbase from here.
  2. mvn spring-boot:run

Let’s add an entity class representing JSON document which we want to persist:

Please notice the annotations which we have used in the Data Model define above.

@Document: Identifies a domain object to be persisted to Couchbase.
@Id: Identifies a field which will not be stored in the document but rather used as the                      document ID
@Field: Denotes a field in the Couchbase document.

Creating Repository:

Spring framework provides an interface for generic CRUD operations on a repository for a specific type which we can readily use to perform basic CRUD operations

public interface BlogRepository extends CrudRepository<Blog, String> {
   
}

We can even add derivable query methods in the repository, for example,

Blogs findByAuthor(String author);

List deleteBytopicAndAuthor(String title, String author);

You can read more about derivable queries from here.

For integrating the repository with the rest API to be able to perform CRUD operations, we need to define a controller class.

We have used @Autowired annotation on BlogRepository. When the annotation is used on a constructor, an instance of BlogRepository is injected as an argument to the constructor when BlogController is created.

Adding Couchbase configurations:

Before running our application we need to create a bucket in Couchbase and also create a primary index to be able to query on all fields.

Finally, we are ready to run our application and perform all the crud operations!
Find the complete code here. Refer to Readme.md for all the request samples.

I hope you enjoyed reading the blog. Thanks.
Happy blogging!!

References:


Knoldus-blog-footer-image

Written by 

I am a Software Consultant and has experience of more than 1.5 years. I like to study and write about latest technologies.

Knoldus Pune Careers - Hiring Freshers

Get a head start on your career at Knoldus. Join us!