Java Application Development Using Couchbase

In this tutorial we will learn the basics of developing a Java application using Couchbase.

Getting the JAR Files

Get the latest Java client JAR files from here. You can either get the JAR files from Maven repository if you are using the Maven build system. Otherwise, you can download the ZIP file and get the JAR files from there. In client API version 1.3.2, you will need to add these JAR files to your class path and build path:

  • commons-codec-1.5.jar
  • couchbase-client-1.2.0.jar
  • httpcore-4.1.1.jar
  • httpcore-nio-4.1.1.jar
  • jettison-1.1.jar
  • netty-3.5.5.Final.jar
  • spymemcached-2.10.0.jar

In addition, you will need a JSON library that can serialize Java objects into JSON and back. I recommend using Gson. This, you can download from here. Gson needs only one JAR file, for example: gson-2.2.4.jar.

If you are writing a web application, add all of these JAR files to WEB-INF/lib folder.

Opening a Connection

The steps to open a new connection is as follows:

List<URI> hosts = Arrays.asList(new URI("http://127.0.0.1:8091/pools"));
// Name of the Bucket to connect to
String bucket = "default";
// Password of the bucket (empty) string if none
String password = "";

// Connect to the Cluster
CouchbaseClient client = new CouchbaseClient(hosts, bucket, password);

To close the connection:

client.shutdown();

Connection Pooling?

There is no need for connection pooling with Couchbase. The client library uses multiplexing. That is, a single socket is used to serve multiple different channels of communication. A web application can open a single connection and use it from multiple threads. Couchbase doesn’t have any notion of a transaction. So, the operations performed by one thread doesn’t need to be distinguished from the operations from another thread.

If you are using CDI, you can create a singleton class to simplify connection management.

@ApplicationScoped
public class ConnectionManager {
    Logger logger = Logger.getLogger(getClass().getName());
    private CouchbaseClient client;

    @PostConstruct
    public void init() {
        try {
            logger.info("Opening couchbase connection.");
            List<URI> hosts = Arrays.asList(new URI("http://127.0.0.1:8091/pools"));

            // Name of the Bucket to connect to
            String bucket = "default";

            // Password of the bucket (empty) string if none
            String password = "";

            // Connect to the Cluster
            client = new CouchbaseClient(hosts, bucket, password);
        } catch (Exception e) {
            client = null;
            throw new IllegalStateException(e);
        }
    }

    @PreDestroy
    public void destroy() {
        logger.info("Closing couchbase connection.");
        if (client != null) {
            client.shutdown();
            client = null;
        }
    }

    public CouchbaseClient getClient() {
        return client;
    }
}

Getting the connection from any CDI managed class, including Servlet, JSF managed beans and EJB becomes easy.

@WebServlet("/DemoServlet")
public class DemoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Inject
    ConnectionManager cm;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
        CouchbaseClient c = cm.getClient();

        //No need to close connection here.
    }
}

You don’t have to close the connection. The connection stays open for the life of the web application. The @PreDestroy method of the ConnectionManager class will close the connection when the application shuts down.

Storing Documents

In our example, we will use the following document syntax:

{
    id: "ABC1234",
    type: "Story",
    user: "billybob",
    genre: "ghost",
    text: "It was a dark and stormy night..."
}
{
    id: "MNO567",
    type: "Story",
    user: "billybob",
    genre: "adventure",
    text: "The ship sailed at night..."
}
{
    id: "XYZ890",
    type: "Story",
    user: "jane13",
    genre: "ghost",
    text: "The house stood at the end of a narrow road..."
}

The corresponding Java class will be:

public class Story implements Serializable {
    private static final long serialVersionUID = 2137881606866283873L;

    private String id;
    private String type;
    private String user;
    private String genre;
    private String text;

    //Getters and setters....
}

A couple of things to note here:

  • Every document in Couchbase must have a unique ID. This ID is stored separate from the document itself and you don’t have to include the ID within the document. I find it convenient to see the ID within the document. This is why I have the “id” field with the document as well as in the Java class.
  • I highly recommend adding a type field that describes the nature of the document. This serves the same purpose as a table name in a relational database. It is a namespace. Couchebase doesn’t have a notion of table names. To distinguish different types of documents, the type field comes handy. I usually set the type to the same name as the Java class – “Story” in our case.
  • The Java class needs to be serializable for Gson to serialize objects into JSON and back. If you have a variable that should not be serialized, mark it as transient.

We add (insert) a new Story document like this:

CouchbaseClient c = ...;

Story s = new Story();

s.setId(UUID.randomUUID().toString());
s.setGenre("ghost");
s.setType("Story");
s.setUser("billybob");
s.setText("It was a dark and stormy night...");

Gson gson = new Gson();
String json = gson.toJson(s);

c.add(s.getId(), json);

The add() method is used to insert a new document. The replace() method is used to update an existing document. If the document does not exist replace() fails. There is also the set() method. This implicitly does an add() if a document doesn’t exist. Otherwise, it does a replace().

To delete a document, call the delete() method of the client.

Looking Up a Document

You can look up a document JSON string using the get() method. Then convert the JSON into a Java object.

CouchbaseClient c = ...;

Gson gson = new Gson();
String json = (String) c.get("1ac900aa-6092-4a4a-958b-bb08f8076ebf");
Story s = gson.fromJson(json, Story.class);

That’s all for today. I will do another tutorial on querying using views.

3 thoughts on “Java Application Development Using Couchbase

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s