Couchbase Server Quickstart - Java with Couchbase SDK 3 and IntelliJ

    +
    Using Intellij and Couchbase Java SDK 3 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 Couchbase Dependency

    To add Couchbase as a dependency, simply add following block above the tag </project> near the end of your pom.xml file:

    <dependencies>
        <dependency>
            <groupId>com.couchbase.client</groupId>
            <artifactId>java-client</artifactId>
            <version>3.0.3</version>
        </dependency>
    </dependencies>
    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>com.couchbase.client</groupId>
            <artifactId>java-client</artifactId>
            <version>3.0.3</version>
          </dependency>

    Step 3: Connecting to Couchbase

    We will build a simple line command app. Let’s start by creating a new class called QuickStartCouchbase to show how to connect with Couchbase:

    import com.couchbase.client.java.*;
    import com.couchbase.client.java.document.*;
    import com.couchbase.client.java.document.json.*;
    import com.couchbase.client.java.query.*;
    
    public class QuickStartCouchbase {
    
        public static void main(String[] args) {
    
            String bucketName = "default";
            String username = "Administrator";
            String password = "password";
            Cluster cluster = null;
            Bucket bucket = null;
    
            try {
    
                // Initialize the Connection
                cluster = Cluster.connect("localhost", username, password);
                bucket = cluster.bucket(bucketName);
                // get a collection reference
                Collection collection = bucket.defaultCollection();
    
    
            } catch (Exception e ) {
                System.out.println("Ooops!... something went wrong");
                e.printStackTrace();
            } finally {
    
                //Naive way to just close a single bucket
                if(bucket != null) {
                    bucket.close();
                }
    
                // Disconnect and close all buckets
                if(cluster != null) {
                    cluster.disconnect();
                }
            }
    
        }
    }
    It is very important that cluster and bucket instances are created during startup and are then reused until the application shuts down. Connection setup is expensive and the SDK is designed to be thread safe and can be efficiently used across all your application threads.

    The cluster and bucket objects can be reused in your application, the most common pattern is to create a Singleton returning them. You can read more about how to manage your connection here.

    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?",
        "type" : "user"
    }
    
    //user::0002
    {
        "firstName" : "Major",
        "lastName" : "Tom",
        "email" : "major.tom@acme.com",
        "tagLine" : "Send me up a drink",
        "type" : "user"
    }
    
    //user::0003
    {
        "firstName" : "Jerry",
        "lastName" : "Wasaracecardriver",
        "email" : "jerry.wasaracecardriver@acme.com",
        "tagLine" : "el sob number one",
        "type" : "user"
    }

    The code to store this data would look like the following:

        JsonObject u1 = JsonObject.create()
                .put("firstName", "Perry")
                .put("lastName", "Mason")
                .put("email", "perry.mason@acme.com")
                .put("type", "user")
                .put("tagLine", "Who can we get on the case?");
    
        MutationResult user1Result = collection.upsert("user::0001", u1);
    
        JsonObject u2 = JsonObject.create()
                .put("firstName", "Major")
                .put("lastName", "Tom")
                .put("email", "major.tom@acme.com")
                .put("type", "user")
                .put("tagLine", "Send me up a drink");
    
        MutationResult user2Result = collection.upsert("user::0002", u2);
    
        JsonObject u3 = JsonObject.create()
                .put("firstName", "Jerry")
                .put("lastName", "Wasaracecardriver")
                .put("email", "jerry.wasaracecardriver@acme.com")
                .put("type", "user")
                .put("tagLine", "el sob number one");
    
        MutationResult user3Result = collection.upsert("user::0003", u3);
    Since SDK 3.0 all Key-Value operations are executed on the collection level instead of the bucket level.

    To recover the document by the id, you can use the method get"

        GetResult getResult = collection.get("user::0001");
        System.out.println(getResult);

    Finally, here is how you query the database when you need all users where the email ends with @acme.com:

        QueryResult result = cluster.query(
                "SELECT * FROM `" + bucketName + "` WHERE email = $email",
                QueryOptions.queryOptions().parameters(JsonObject.create().put("email", "%@acme.com"))
        );
    
        // Print each found Row
        for (JsonObject row : result.rowsAsObject()) {
            System.out.println("Found row: " + row);
        }

    Here is all of the code for our class:

    import com.couchbase.client.java.*;
    import com.couchbase.client.java.kv.*;
    import com.couchbase.client.java.json.*;
    import com.couchbase.client.java.query.*;
    
    public class QuickStartCouchbase {
    
        public static void main(String[] args) {
    
            String bucketName = "default";
            String username = "Administrator";
            String password = "password";
            Cluster cluster = null;
    
            try {
    
                // Initialize the Connection
                cluster = Cluster.connect("localhost", username, password);
                Bucket bucket = cluster.bucket(bucketName);
                // get a collection reference
                Collection collection = bucket.defaultCollection();
    
                JsonObject u1 = JsonObject.create()
                        .put("firstName", "Perry")
                        .put("lastName", "Mason")
                        .put("email", "perry.mason@acme.com")
                        .put("type", "user")
                        .put("tagLine", "Who can we get on the case?");
    
                MutationResult user1Result = collection.upsert("user::0001", u1);
    
                JsonObject u2 = JsonObject.create()
                        .put("firstName", "Major")
                        .put("lastName", "Tom")
                        .put("email", "major.tom@acme.com")
                        .put("type", "user")
                        .put("tagLine", "Send me up a drink");
    
                MutationResult user2Result = collection.upsert("user::0002", u2);
    
                JsonObject u3 = JsonObject.create()
                        .put("firstName", "Jerry")
                        .put("lastName", "Wasaracecardriver")
                        .put("email", "jerry.wasaracecardriver@acme.com")
                        .put("type", "user")
                        .put("tagLine", "el sob number one");
    
                MutationResult user3Result = collection.upsert("user::0003", u3);
    
                GetResult getResult = collection.get("user::0001");
                System.out.println(getResult);
    
                QueryResult result = cluster.query(
                        "SELECT * FROM `" + bucketName + "` WHERE email like $email",
                        QueryOptions.queryOptions().parameters(JsonObject.create().put("email", "%@acme.com"))
                );
    
                // Print each found Row
                for (JsonObject row : result.rowsAsObject()) {
                    System.out.println("Found row: " + row);
                }
    
            } catch (Exception e ) {
                System.out.println("Ooops!... something went wrong");
                e.printStackTrace();
            } finally {
    
                // Disconnect and close all buckets
                if(cluster != null) {
                    cluster.disconnect();
                }
            }
    
        }
    }
    Make sure you have at least a primary index in your bucket before running the code.

    If you want to run the code to see its output, right-click on the class and choose "Run":