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:



This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters


<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-couchbase</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
view raw

pom.xml

hosted with ❤ by GitHub

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:



This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters


package com.knoldus.blogs.models;
import com.couchbase.client.java.repository.annotation.Field;
import com.couchbase.client.java.repository.annotation.Id;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import org.springframework.data.couchbase.core.mapping.Document;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Date;
import java.util.List;
@Builder
@Data
@AllArgsConstructor
@Document
public class Blogs {
@Id
final String id;
@Size(min=10)
@NotNull
@Field
String topic;
@NotNull
@Field
String author;
@Field
List<String> tags;
@Field
Date date;
}
view raw

Blogs.java

hosted with ❤ by GitHub

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.



This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters


package com.knoldus.blogs.controller;
import com.knoldus.blogs.models.Blogs;
import com.knoldus.blogs.models.BlogsUpdateRequest;
import com.knoldus.blogs.repository.BlogRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Optional;
@RestController
public class BlogController {
@Autowired
BlogRepository blogRepository;
@RequestMapping("/")
public String index() {
return "Welcome to the CRUD application!!";
}
@PostMapping("/blogs")
public Blogs addBlogPost(@RequestBody Blogs newBlog) {
return blogRepository.save(newBlog);
}
@GetMapping("/blogs/{id}")
public Optional<Blogs> getBlog(@PathVariable String id) {
if (blogRepository.existsById(id)) {
return blogRepository.findById(id);
} else
return Optional.empty();
}
@GetMapping("/blogs/author/{author}")
public Blogs getBlogByAuthorName(@PathVariable String author) {
return blogRepository.findByAuthor(author);
}
@DeleteMapping("/blogs/topic/{topic}/author/{author}")
public List<Blogs> deleteByAuthorAndTopic(@PathVariable String topic, @PathVariable String author) {
return blogRepository.deleteBytopicAndAuthor(topic, author);
}
@DeleteMapping("/blogs/{id}")
public void deleteById(@PathVariable String id) {
blogRepository.deleteById(id);
}
@PutMapping("/blogs/{idToBeUpdated}")
public String updateBlog(@PathVariable String idToBeUpdated, @RequestBody BlogsUpdateRequest blogsUpdateRequest) {
Optional<Blogs> mayBeBlog = blogRepository.findById(idToBeUpdated)
.map(blogs -> blogRepository
.save(Blogs
.builder()
.id(idToBeUpdated)
.topic(blogsUpdateRequest.getTopic())
.tags(blogsUpdateRequest.getTags())
.author(blogs.getAuthor())
.date(blogs.getDate())
.build())
);
if (mayBeBlog.isPresent()) {
return "Blog Updated";
} else {
return "Blog does not exist";
}
}
}

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:



This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters


package com.knoldus.blogs;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.couchbase.config.AbstractCouchbaseConfiguration;
import java.util.Collections;
import java.util.List;
@Configuration
public class Config extends AbstractCouchbaseConfiguration {
@Override
protected List<String> getBootstrapHosts() {
return Collections.singletonList("127.0.0.1");
}
@Override
protected String getBucketName() {
return "blog";
}
@Override
protected String getBucketPassword() {
return "knoldus";
}
@Override
protected String getUsername() {
return "Administrator";
}
}
view raw

Config.java

hosted with ❤ by GitHub

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.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading