Data

Spring Data Couchbase Example

In this example we shall demonstrate how we can connect Spring Data with Couchbase.

1. What is CouchBase?

Couchbase is a highly scalable, Document based NoSQL Database. Document based NoSQL databases work on map-like concept of KEY-VALUE pairs. The key being uniquely identifiable property like a String, path etc and the value being the Document that is to be saved. Another example of Document based NoSQL is MongoDB. In one of our previous examples, we have already demonstrated how we can connect and manage Spring Data with MongoDB.

Spring Data CouchBase is the Spring module which helps us in integrating with the CouchBase Database Server.As with the other modules demonstrated in this series, this module too provides supports both for derived queries(based on the method names) and the annotated query.

2. Project Set-Up

So, let’s start the project setup by installing CouchBase Database Server from here. We have used the Community Edition for this example.

Upon successful installation the user will be directed to this page : http://localhost:8091/index.html

Here is how the page looks like:

Fig 1 : Successful Couchbase Setup
Fig 1 : Successful Couchbase Setup

Next step is to create a new Data-Bucket. Data-Bucket is like analogous to a Table in RDBMS or to a Collection in a MongoDb Database. This can done by clicking on the Create New Data Bucket button present on the Data Buckets tab. We are naming it JavaCodeGeeks for the sake of this example. We shall be adding our documents to this data bucket.

Now that the CouchBase server is up and running, we will setup the application environment.
Create a simple Maven Project in Eclipse IDE by selecting the Skip Archetype Selection checkbox from the New Maven Project Pop-up. We are using the below pom.xml to manage the dependencies for CouchBase from Spring Data.

pom.xml

<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.jcg.examples.springDataCouchbaseExample</groupId>
	<artifactId>SpringDataCouchbaseExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-couchbase</artifactId>
			<version>2.0.0.RELEASE</version>
		</dependency>

	</dependencies>

</project>

Eclipse will download the required JAR files and add the dependencies in the project classpath. Now that the project is setup and dependencies imported, we can begin writing the actual code.

3. Implementation

The implementation will consist of three major configuration files. The first one is the actual domain object which will be persisted in the CouchBase Database as the Document.

Book.java

package com.jcg.examples.entity;

import org.springframework.data.couchbase.core.mapping.Document;

import com.couchbase.client.java.repository.annotation.Field;
import com.couchbase.client.java.repository.annotation.Id;

@Document(expiry=0)
public class Book
{

		@Id
		private long bookId;
		
		@Field
		private String name;
		
		@Field
		private long isbnNumber;

		public long getBookId()
		{
				return bookId;
		}

		public void setBookId(long bookId)
		{
				this.bookId = bookId;
		}

		public String getName()
		{
				return name;
		}

		public void setName(String name)
		{
				this.name = name;
		}

		public long getIsbnNumber()
		{
				return isbnNumber;
		}

		public void setIsbnNumber(long isbnNumber)
		{
				this.isbnNumber = isbnNumber;
		}

		@Override
		public String toString()
		{
				return "Book [bookId=" + bookId + ", name=" + name + ", isbnNumber=" + isbnNumber + "]";
		}
		
}

@Document annotation is used to mark the PoJo as the Couchbase Document. It has an expiry attribute which is the TTL of the document.

@Id marks the corresponding instance variable as document Id in the database.We shall retrieve the document later based on this Id.

Next is the basic Repository Class:

BookRepo.java

package com.jcg.examples.repo;

import org.springframework.data.couchbase.repository.CouchbaseRepository;
import org.springframework.stereotype.Repository;

import com.jcg.examples.entity.Book;

@Repository
public interface BookRepo extends CouchbaseRepository<Book, Long>
{
}

The repo simply extends from the org.springframework.data.couchbase.repository.CouchbaseRepository interface and the implementation is provided by the Spring container at the run-time. We need to provide declare the proper Generics as per the Entity, which in our case is the . Spring Data Module provides us with a number of inbuilt method for manipulating the Data. We need not write the queries for basic data manipulation and reading.

For executing custom written queries, the developer can create his own method by specifying the Query using the org.springframework.data.couchbase.core.query.Query annotation.

Lastly, and most important is the XML based configuration to initiate the Couchbase datasource so that we can communicate and execute our queries against the Server.

spring-couchbase-integration.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:couchbase="http://www.springframework.org/schema/data/couchbase"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
    http://www.springframework.org/schema/data/couchbase
    http://www.springframework.org/schema/data/couchbase/spring-couchbase.xsd">

    <couchbase:cluster>
      <couchbase:node>127.0.0.1</couchbase:node>
    </couchbase:cluster>

    <couchbase:clusterInfo  login="Administrator" password="Administrator"/>
	
	<beans:bean id="couchbaseEnv" class="com.couchbase.client.java.env.DefaultCouchbaseEnvironment" factory-method="create"/>
	<beans:bean id="myCustomTranslationService" class="org.springframework.data.couchbase.core.convert.translation.JacksonTranslationService"/>
	
	<couchbase:indexManager/>
	
	<couchbase:repositories base-package="com.jcg.examples.repo" />
	
	 <couchbase:template translation-service-ref="myCustomTranslationService"/>

    

    <couchbase:bucket bucketName="JavaCodeGeeks" bucketPassword="password.1"/>
</beans:beans>

That is all from the setup point of view. Now that all is set, let’s run the application and test out the code! Here’s ApplicationTest class that loads the XML file to instantiate the Spring Container and execute a few queries.

ApplicationTest.java

package com.jcg.examples;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

import com.jcg.examples.entity.Book;
import com.jcg.examples.repo.BookRepo;

public class ApplicationTest
{

		
		public static void main(String[] args)
		{
				ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new ClassPathResource("spring-couchbase-integration.xml").getPath());
				BookRepo bookRepo = context.getBean(BookRepo.class);
				
				Book book = new Book();
				book.setBookId(123);;
				book.setIsbnNumber(2133443554);
				book.setName("Kane And Abel by XYZ");
				bookRepo.save(book);
				
				Book anotherBook = new Book();
				anotherBook.setBookId(456);;
				anotherBook.setIsbnNumber(2133443554);
				anotherBook.setName("The Prodigal Daughter");
				bookRepo.save(anotherBook);
				
				Book retreivedBook = bookRepo.findOne(123l);
				
				System.out.println(retreivedBook);
				
				bookRepo.delete(456l);
				
				context.close();
		}

}

We have created two Book objects and persisted them as documents in the Database. Then we will try to retrieve them by their Id and delete one of them by passing their ID.

Here’s the sample output of the program:

INFO: Connected to Node 127.0.0.1
Feb 28, 2016 12:41:27 AM com.couchbase.client.core.config.DefaultConfigurationProvider$8 call
INFO: Opened bucket JavaCodeGeeks
Book [bookId=123, name=Kane And Abel by XYZ, isbnNumber=2133443554]

In the UI console, the user can see the save Documents under the Data-Buckets>Documents Tab. Here’s what it looks like :

Fig 2 : CouchBase Save Example
Fig 2 : CouchBase Save Example

And the detailed Document View:

Fig 3 : Saved Document details
Fig 3 : Saved Document details

4. Download the Source Code

Here we demonstrated how to configure and manage a Couchbase Database Server using Spring Data.

Download
You can download the source code of this example here: SpringDataCouchbaseExample.zip

Chandan Singh

Chandan holds a degree in Computer Engineering and is a passionate software programmer. He has good experience in Java/J2EE Web-Application development for Banking and E-Commerce Domains.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Manjesh Savita
Manjesh Savita
4 years ago

this example is not working

Back to top button