Using Java to Operate Couchbase
To use Java to operate Couchbase, you can follow the following steps:
1. Add Maven dependencies for the Couchbase Java SDK to your project.
<dependency>
<groupId>com.couchbase.client</groupId>
<artifactId>java-client</artifactId>
<version>3.1.4</version>
</dependency>
2. Create a connection to a Couchbase cluster
Cluster cluster = Cluster.connect("localhost", "username", "password");
3. Select a bucket to manipulate data
Bucket bucket = cluster.bucket("bucketName");
4. Insert Data
JsonObject jsonObject = JsonObject.create()
.put("id", "1")
.put("name", "John Doe")
.put("age", 30);
bucket.defaultCollection().upsert("documentKey", jsonObject);
5. Modify data
bucket.defaultCollection().mutateIn("documentKey")
.upsert("name", "Updated Name")
.execute();
6. Query Data
GetResult getResult = bucket.defaultCollection().get("documentKey");
JsonObject resultJson = getResult.contentAs(JsonObject.class);
System.out.println(resultJson);
7. Delete data
bucket.defaultCollection().remove("documentKey");
This is a complete Java code sample that demonstrates how to use the Java operation Couchbase to insert, modify, query, and delete data.
import com.couchbase.client.core.error.DocumentNotFoundException;
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.Cluster;
import com.couchbase.client.java.Collection;
import com.couchbase.client.java.json.JsonObject;
import com.couchbase.client.java.kv.GetResult;
public class CouchbaseExample {
public static void main(String[] args) {
Cluster cluster = Cluster.connect("localhost", "username", "password");
Bucket bucket = cluster.bucket("bucketName");
Collection collection = bucket.defaultCollection();
//Insert Data
JsonObject jsonObject = JsonObject.create()
.put("id", "1")
.put("name", "John Doe")
.put("age", 30);
collection.upsert("documentKey", jsonObject);
//Modify data
collection.mutateIn("documentKey")
.upsert("name", "Updated Name")
.execute();
//Query data
try {
GetResult getResult = collection.get("documentKey");
JsonObject resultJson = getResult.contentAs(JsonObject.class);
System.out.println(resultJson);
} catch (DocumentNotFoundException e) {
System.out.println("Document not found");
}
//Delete data
collection.remove("documentKey");
cluster.disconnect();
}
}
Ensure that the 'localhost', 'username', 'password', and 'bucketName' in the replacement code are your Couchbase server address, username, password, and correct bucket name.