In this introduction tothe Couchbase SDK for Java,we demonstratehow tointeract withaCouchbase document database, covering basic concepts such as creating a Couchbase environment, connecting to a cluster, openingdata buckets, using the basic persistence operations, and working with document replicas.
2. Maven DependenciesIf you are using Maven, add the following to your pom.xml file:
<dependency><groupId>com.couchbase.client</groupId>
<artifactId>java-client</artifactId>
<version>2.2.6</version>
</dependency> 3.Getting Started
The SDK providesthe CouchbaseEnvironment interface and animplementation class DefaultCouchbaseEnvironment containing default settings for managing access to clusters and buckets. The default environment settings can be overridden if necessary, as we will see in section 3.2.
Important:The official Couchbase SDK documentation cautionsusers toensure that only one CouchbaseEnvironment is active in the JVM, since the use oftwo or moremay result in unpredictablebehavior.
3.1. Connecting to a Cluster with a Default EnvironmentTo have the SDK automatically create a CouchbaseEnvironment with default settings and associate it with our cluster, we can connectto thecluster simply by providing the IP address or hostname ofone or more nodes in the cluster.
In this example, weconnect to a single-node cluster on ourlocal workstation:
Cluster cluster = CouchbaseCluster.create("localhost");To connect to a multi-node cluster, we would specify at least two nodes in case one of themis unavailable when the application attempts toestablish the connection:
Cluster cluster = CouchbaseCluster.create("192.168.4.1", "192.168.4.2");Note:It is not necessary to specify every node in the cluster when creating the initial connection.The CouchbaseEnvironment will query the cluster once the connection is establishedin orderto discovertheremaining nodes (if any).
3.2. Using a Custom EnvironmentIf yourapplication requires fine tuning of any of the settings provided by DefaultCouchbaseEnvironment , you can create a custom environment and then use that environment when connecting to your cluster.
Here’s an example that connects to a single-node cluster using acustom CouchbaseEnvironment with a ten-second connection timeout and a three-second key-value lookup timeout:
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder().connectTimeout(10000)
.kvTimeout(3000)
.build();
Cluster cluster = CouchbaseCluster.create(env, "localhost");
And to connect to a multi-node cluster with the custom environment:
Cluster cluster = CouchbaseCluster.create(env,"192.168.4.1", "192.168.4.2"); 3.3. Opening a Bucket
Once you have connected to the Couchbase cluster, you can open one or more buckets.
When you first set up a Couchbase cluster, the installation package automatically creates abucket named “default” with a blank password.
Here’sone way toopen the “default” bucket when it hasa blank password:
Bucket bucket = cluster.openBucket();You can also specify the bucket name when opening it:
Bucket bucket = cluster.openBucket("default");For any otherbucketwith a blankpassword, you must supply the bucket name:
Bucket myBucket = cluster.openBucket("myBucket");To open abucket that hasa non-blank password, you must supply the bucket name and password:
Bucket bucket = cluster.openBucket("bucketName", "bucketPassword"); 4. Persistence OperationsIn this section,we show how to perform CRUD operations in Couchbase.In ourexamples, we will be working with simple JSON documents representing a person, as in this sample document:
{"name": "John Doe",
"type": "Person",
"email": "john.doe@mydomain.com",
"homeTown": "Chicago"
}
The “type” attribute is not required, howeverit is commonpractice to include an attribute specifying the document typein case one decidesto store multiple types inthe same bucket.
4.1. DocumentIDsEach document stored in Couchbase is associated with an id thatis unique to the bucket in which the document is being stored. The document id isanalogous to the primary key column in a traditional relational database row.
Document id values must be UTF-8 strings of 250 or fewer bytes.
Since Couchbase does not provide a mechanism for automatically generating the id on insertion, we must provide our own.
Common strategies for generating ids include key-derivation usinga natural key, such as the “email” attribute shown in our sample document, andthe use of UUID strings.
For our examples, we will generate random UUID strings.
4.2. Insertinga DocumentBefore we can insert a new document into our bucket, we must first createan instance of JSONObject containing the document’scontents:
JsonObject content = JsonObject.empty().put("name", "John Doe")
.put("type", "Person")
.put("email", "john.doe@mydomain.com")
.put("homeTown", "Chicago");
Next, we create a JSONDocument object consisting of an id value and the JSONObject :
String id = UUID.randomUUID().toString();JsonDocument document = JsonDocument.create(id, content);
To adda new document to the bucket, we use the insert method:
JsonDocument inserted = bucket.insert(document);The JsonDocument returned contains all of the properties of the original document, plus a value known as the “CAS” (compare-and-swap) value that Couchbase uses for version tracking.
If a document with the supplied id already exists in the bucket, Couchbase throws a DocumentAlreadyExistsException .
We can also use the upsert method, which will either insert the document (if the id is not found) or update the document (if the id is found):
JsonDocument upserted = bucket.upsert(document); 4.3. Retrievinga DocumentTo retrieve a document by its id , we use the get method:
JsonDocument retrieved = bucket.get(id);If no document exists with the given id , the method returns null .
4.4. Updating or Replacing a DocumentWe can update an existing document using the upsert method:
JsonObject content = document.content();content.put("homeTown", "Kansas City");
JsonDocument upserted = bucket.upsert(document);
As we mentioned in section 4.2, upsert will succeed whether a document with the given id was found or not.
If enough time has passedbetween the time we originally retrieved the document and our attempt to upsert the revised document, there is apossibility that the originaldocument will havebeen deleted from the bucket by another process or user.
If we need toguard against this scenario in our application, we can instead use the replace method, which failswith a DocumentDoesNotExistException if adocument