In this blog, we will learn to implement CRUD operations in Couchbase with a Java application.
So, let’s begin with a quick introduction of the Couchbase Server.
Introduction to Couchbase
Couchbase Server is an open source, distributed, NoSQL document-oriented engagement database with many advantages over traditional RDBMS like:-
- Fast key-value store with managed cache for sub-millisecond data operations.
- Purpose-built indexers for fast queries.
- A powerful query engine for executing SQL-like queries.
- Can run natively on-device and manages synchronization to the server.
- Provide low-latency data management.
It is a document database at its core, as it stores keys and values as JSON documents(if they are valid JSON).
Here’s a comparison of how data is stored in RDBMS vs. Document Oriented Database.
For more information, See: Couchbase Documentation
Enough introduction? So let’s proceed with how to interact with the Couchbase Server to perform the basic CRUD operations on the Couchbase documents & buckets.
Install and Setup Couchbase Java SDK
Add a Couchbase Java Client
To perform CRUD operations through Java, A couchbase java client is required which can be added with the following dependency-
<dependency> <groupId>com.couchbase.client</groupId> <artifactId>java-client</artifactId> <version>2.5.5</version> </dependency>
Establish a connection to the Couchbase Server
Start a Server with default configuration.
final Cluster cluster = CouchbaseCluster.create();
Start a server on a given node.
final Cluster cluster = CouchbaseCluster.create(“127.10.10.20”);
Start a server with a given environment.
final CouchbaseEnvironment env = DefaultCouchbaseEnvironment
final Cluster cluster = CouchbaseCluster.create(env);
This is an important step, as skipping this would require us to authenticate each bucket individually.
These are the default credentials for Couchbase.
Open a Bucket to use
This bucket will be used for all the CRUD operations.
Bucket bucket = cluster.openBucket(“sample-bucket”);
Opens the bucket with the given name, And, If the bucket doesn’t exist already, you will get BucketDoesNotExistException.
However, if you want to create a bucket, you can also create one. See CRUD Operations for Couchbase Buckets.
Disconnecting from the Couchbase Server
You need to make sure to disconnect properly from the cluster to free all resources when your application shuts down.
Using the SDK: CRUD Operations for Couchbase Documents
We will be using JsonDocument to perform basic CRUD operations with Couchbase Server and Java SDK, as the SDK comes with built-in handling for JSON documents.
JsonDocument is a public class in Couchbase Java Client and one of the most integral parts of the API. It is intended to be used as a canonical wrapper around retrieval and mutation operations, abstracting away JSON internals.
A documentId is the unique identifier for the document.
final String documentId = “user-doc”;
JsonObject user = JsonObject.create()
.put(“job”, “Software Consultant”);
JsonDocument document = JsonDocument.create(documentId, user);
Be careful, An attempt to insert a document that is already present in the bucket will result in DocumentAlreadyExistsException.
Create a new JsonObject or modify an existing one to update the document.
Here, we are modifying an existing user.
JsonObject updatedUser = user
Use the documentId of the Document to be updated.
If you care about concurrent updates, use replace() instead.
Remove the document from the bucket.
JsonDocument resultantDocument = bucket.get(documentId);
You can use this JsonDocument for retrieving values further from the resultant JSON.
String firstname = resultantDocument.content().getString(“firstname”);
Using the SDK: CRUD Operations for Couchbase Buckets
BucketSettings sampleBucket = new DefaultBucketSettings.Builder() .type(BucketType.COUCHBASE) .name("new-bucket") .port(0) .quota(100) // megabytes .replicas(1) .indexReplicas(true) .enableFlush(true) .build();
This will create a new bucket with the given properties. You can customize the bucket settings as required. But this bucket is not added to the cluster yet. So, let’s insert the newly created bucket into the cluster with the next step.
Also, if you want to provide a timeout while inserting the bucket, you can do this by-
cluster.clusterManager(USERNAME, PASSWORD).insertBucket(sampleBucket, 10000, TimeUnit.MILLISECONDS);
You may encounter BucketAlreadyExists Exception If a bucket with the same name already exists.
To use any bucket, we must open it first with the following step-
Bucket bucket = cluster.openBucket(BUCKET_NAME); //Using the bucket to insert a new JsonDocument. bucket.insert(JsonDocument.create("document-id"));
This was all about the basic CRUD in couchbase, however, we can do much more like querying documents using the Couchbase Java SDK, but we’ll cover that in the upcoming blog.
Hope this is helpful for you, Please feel free to comment for any queries.