Couchbase Server Quickstart - Java with Spring Data Couchbase and IntelliJ

    +
    Using Intellij and Spring Data Couchbase SDK to create new database records in Couchbase and look them up.

    Prerequisite: Run Couchbase Server

    1. Couchbase Server 6.5 is already running.

      • An empty bucket named "default" has been created.

      • Both a primary index and an adaptive index have been created and built on the default bucket.

      • If you still need to perform these tasks please use the following:

    2. IntelliJ is installed. If you don’t have it installed yet, follow this tutorial.

    3. Java 8 or higher is installed.

    Step 1: Start a New Project on IntelliJ

    Open IntelliJ and create a new project.

    New Project dialog in IntelliJ

    Select the Maven template in the next dialog:

    Template select in IntelliJ

    Inform a name for your project and click on Finish:

    Project name in IntelliJ

    In the end, your project should look similar to the following:

    Project name in IntelliJ

    Now, right-click on the java folder of your project and select new → package and choose a name for your new package:

    Create Package

    You can create new classes by right-clicking on your package name and selecting new → Java Class:

    Step 2: Adding Spring and Couchbase Dependencies

    Now let’s update your project with all the dependencies we need. I will assume that your application is a web project, and to make things easier, we will also use Spring Boot in this tutorial.

    The first step is to add following block under the tag called project of your pom.xml file:

        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.2.RELEASE</version>
        </parent>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>

    The code above will configure your application as a spring boot project.

    Next, we will add Couchbase Spring Data as a dependency of your project with the following block:

        <dependencies>
            <dependency>
                <groupId>org.springframework.data</groupId>
                <artifactId>spring-data-couchbase</artifactId>
                <version>3.2.3.RELEASE</version>
            </dependency>
        </dependencies>

    The block above should also be inside the project tag.

    If the <dependencies> tag is already present in your pom.xml file, you should add just the dependency instead:
        <!-- add the block bellow inside the <dependencies> tag -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-couchbase</artifactId>
            <version>3.2.3.RELEASE</version>
        </dependency>

    Your pom.xml file should look like the following:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>org.example</groupId>
        <artifactId>quickstart-couchbase</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.2.RELEASE</version>
        </parent>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.data</groupId>
                <artifactId>spring-data-couchbase</artifactId>
                <version>3.2.3.RELEASE</version>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>

    Step 3: Connecting to Couchbase

    We can push the responsibility of connecting and managing the connection with Couchbase to the Spring Framework. In order to do that, you will need to specify Couchbase’s IP address, bucket name, username, and password in a configuration class that extends AbstractCouchbaseConfiguration. Create a new class called CouchbaseConfig and paste the following content:

    //don't forget to always put your package name here
    package my.pack.name.here
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.couchbase.config.AbstractCouchbaseConfiguration;
    
    import java.util.Arrays;
    import java.util.List;
    
    @Configuration
    public class CouchbaseConfig extends AbstractCouchbaseConfiguration {
    
    
        @Override
        protected List<String> getBootstrapHosts() {
            return Arrays.asList("127.0.0.1");
        }
    
        @Override
        protected String getBucketName() {
            return "default";
        }
    
        @Override
        protected String getUsername(){
            return "Administrator";
        }
    
        @Override
        protected String getBucketPassword() {
            return "password";
        }
    }

    Spring Boot requires a class with a main method to run the project. Create a new class called QuickStartCouchbase and paste the following content:

    //don't forget to always put your package name here
    package my.pack.name.here
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class QuickStartCouchbase {
    
        public static void main(String[] args) {
            SpringApplication.run(QuickStartCouchbase.class, args);
        }
    }

    Finally, right-click on the class above and choose "Run":

    If everything is fine, your application logs should look like the following:

    Project Started successfully
    TIP

    If you get any errors, double-check if the IP address, username, password and bucket name of your Couchbase instance is correct.

    Step 4: Create and query new document

    Suppose we need to store the following data in the database representing 3 distinct users:

    //user::0001
    {
        "firstName" : "Perry",
        "lastName" : "Mason",
        "email" : "perry.mason@acme.com",
        "tagLine" : "Who can we get on the case?"
    }
    
    //user::0002
    {
        "firstName" : "Major",
        "lastName" : "Tom",
        "email" : "major.tom@acme.com",
        "tagLine" : "Send me up a drink"
    }
    
    //user::0003
    {
        "firstName" : "Jerry",
        "lastName" : "Wasaracecardriver",
        "email" : "jerry.wasaracecardriver@acme.com",
        "tagLine" : "el sob number one"
    }

    The respective entity and mapping using Couchbase Spring Data would look like the following:

    //don't forget to always put your package name here
    package my.pack.name.here
    
    import org.springframework.data.annotation.Id;
    import org.springframework.data.couchbase.core.mapping.Document;
    
    @Document
    public class User {
    
        @Id
        private String id;
        private String firstName;
        private String lastName;
        private String email;
        private String tagLine;
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public String getFirstName() {
            return firstName;
        }
    
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }
    
        public String getLastName() {
            return lastName;
        }
    
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
    
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email;
        }
    
        public String getTagLine() {
            return tagLine;
        }
    
        public void setTagLine(String tagLine) {
            this.tagLine = tagLine;
        }
    }

    Create a new class called User and paste the content above.

    By default, all attributes of the class will be directly mapped to the corresponding JSON attribute.

    Note that we have two special annotations in the class above:

    • @Id: (Required) - This annotation tells Spring Data which attribute of the entity represents the primary key of the document.

    • @Document: (Optional) - Identifies a domain object to be persisted as a document in Couchbase.

    Now, let’s create the repository responsible to manage our User entity. Create a new interface named UserRepository extending the CouchbaseRepository class:

    //don't forget to always put your package name here
    package my.pack.name.here
    
    import org.springframework.data.couchbase.repository.CouchbaseRepository;
    import org.springframework.stereotype.Repository;
    
    import java.util.List;
    
    @Repository
    public interface UserRepository extends CouchbaseRepository<User, String> {
    
        List<User> findByEmailLike(String firstName);
    }

    Note that our class is decorated with the @Repository annotation, it is used to indicate that the class provides the mechanism for storage, retrieval, search, update and delete operation on objects.

    We also added in the interface the method findByEmailLike. This method is named that way because it is using the Spring Data DSL. Whenever you use this DSL, Spring automatically generates an implementation for you. Worth to highlight that methods like save, saveAll, delete, deleteById, findById, etc are also automatically generated when you extend the CouchbaseRepository class.

    Using a repository is rather simple: all you need to do is to inject it using the @Autowired annotation.:

    //don't forget to always put your package name here
    package my.pack.name.here
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.stereotype.Component;
    
    import java.util.List;
    import java.util.Optional;
    
    /**
     * Components of the type CommandLineRunner are called right after
     * the application start up. So the method *run* is called as soon as
     * the application starts.
     */
    @Component
    public class CmdRunner implements CommandLineRunner {
    
        @Autowired
        private UserRepository userRepository;
    
    
        @Override
        public void run(String... strings) throws Exception {
    
            User u1 = createUser("user::0001", "Perry", "Manson", "perry.mason@acme.com", "Who can we get on the case?");
            userRepository.save(u1);
    
            User u2 = createUser("user::0002", "Major", "Tom", "major.tom@acme.com", "Send me up a drink");
            userRepository.save(u2);
    
    
            User u3 = createUser("user::0003", "Jerry", "Wasaracecardriver", "jerry.wasaracecardriver@acme.com", "el sob number one");
            userRepository.save(u3);
    
            Optional<User> user = userRepository.findById("user::0001");
            System.out.println("User found = "+user.get().getFirstName());
    
            List<User> result = userRepository.findByEmailLike("%@acme.com");
    
            System.out.println( "Total of @acme.com users = "+result.size()  );
    
        }
    
        public static User createUser(String id, String firstName, String lastName,
                                      String email, String tagLine) {
            User user = new User();
            user.setId(id);
            user.setFirstName(firstName);
            user.setLastName(lastName);
            user.setEmail(email);
            user.setTagLine(tagLine);
            return user;
        }
    
    }

    Create a new class called CmdRunner and paste the content above. Then, go back to your main class (QuickStartCouchbase in this example), and run it again. Don’t forget to stop your application first if it was already running.

    The output should look like the following:

    Application Ran Successfully
    If you forgot to create the required indexes, your application will fail to execute the CmdRunner class. Check out this tutorial or run `create primary index on default`on Couchbase’s Query Workbench. I’m assuming that default is the name of your bucket.

    In the code above, we first create a new instances of the User entity and store them in the database using the save method. This is how all three documents will look like on Couchbase:

    Document Inserted

    In the CmdRunner class we also get the document back using its id user::0001 through the method findById. Finally we query all user documents where email like "%@acme.com" using the method findByEmailLike.

    Note that the id of the document is not stored directly in the body of the JSON, but in a meta space called metadata:

    Document Metadata
    You might have noticed that there is a _class attribute in the JSON file. This attribute is automatically added by Spring Data to represent the type of the document.