Java CouchDB Tutorial

Java CouchDB

To connect to the CouchDB with the Java Programming language, one can use the Ektorp library. It facilitates a persistence layer on top of the CouchDB. Follow the below steps to connect to the CouchDB with the Java Programming language and then to create a database.

  • Create a maven project.
  • Provide a name to your project.
  • Here, “couch-java” is the project name as well as the Artifact ID, “com.example” is the Group ID and “1.0-SNAPSHOT” is the version name.
  • Here, “com.example.java.couchdb” is the package name.
  • Now add the dependency in the “pom.xml” file.

 

Ektorp library dependency:

<dependency>

<groupId>org.ektorp</groupId>

<artifactId>org.ektorp</artifactId>

<version>1.4.4</version>

</dependency>

pom.xml:

<?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>com.example</groupId>

<artifactId>couch-java</artifactId>

<version>1.0-SNAPSHOT</version>

<packaging>jar</packaging>

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<maven.compiler.source>1.8</maven.compiler.source>

<maven.compiler.target>1.8</maven.compiler.target>

</properties>

<dependencies>

<dependency>

<groupId>org.ektorp</groupId>

<artifactId>org.ektorp</artifactId>

<version>1.4.4</version>

</dependency>

</dependencies>

</project>

Create a Java file for connection, after adding the dependency.

<strong>CouchJava.java:</strong>
 
package com.example.java.couchdb;
 
import java.net.MalformedURLException;
 
import org.ektorp.CouchDbConnector;
 
import org.ektorp.CouchDbInstance;
 
import org.ektorp.http.HttpClient;
 
import org.ektorp.http.StdHttpClient;
 
import org.ektorp.impl.StdCouchDbConnector;
 
import org.ektorp.impl.StdCouchDbInstance;
 
import org.ektorp.support.DesignDocument;
 
public class CouchJava {
 
public static void main(String[] args) throws MalformedURLException {
 
HttpClient httpClient = new StdHttpClient.Builder()
 
.url("http://localhost:5984")
 
.build();
 
CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
 
CouchDbConnector db = new StdCouchDbConnector("example", dbInstance);
 
db.createDatabaseIfNotExists();
 
DesignDocument dd = new DesignDocument("xyz");
 
db.create(dd);
 
}
 
}

Verify the CouchDB connection working, before executing the Java code.

  • Open the URL http://localhost:5984/_utils/.
  • All the available databases will thus be displayed.
  • Now to create a database, execute the Java code.
  • The database will thus be displayed in the database list.
  • Thus the database list in the CouchDB index web page now also includes a database named “example” that contains a document named “xyz”.