Spring Data 2# - support for Couchbase

In this article we will have a look at how NoSQL Couchbase database is supported in Spring, especialy in Spring Data module. Couchbase is a document oriented NoSQL database which has gained a lot of popularity in the last few years. The main reason for that may be its specialization in a low latency data management for large scale web applications.


Couchbase introduction

Couchbase is a NoSQL document database which is a subset of a key-value stores. It is designed to store and retrieve data in JSON format. Each separate JSON item stored in the database is called a document. Couchbase does not force any specific schema on the data that is stored. It is often said that in NoSQL databases any schema specific constraints are moved from the database layer to the application layer. It often provides a better ways to develop a software with dynamic data structure changes since changes in the documents structure do not break any database constraints or schema. In this case you can update the data model on the application side in an agile and quick way without a need to perform additional changes in the database layer. As it is written in its documentation (Couchbase documentation), Couchbase is specialized in providing a low latency data management for large-scale interactive web, mobile and IoT application.


Configuration with SpringBoot and SpringData

Spring Data contains a Spring Data Couchbase library which provides an integration and abstraction over Couchbase database. The two important functionalities distributed with Spring Data Couchbase are:
  • Possibility of representing Couchbase documents using properly annotated POJO Java classes.
  • Support for defining data access layer with repository interfaces. 
To learn more about Spring Data Couchbase library you can read the documentation: Spring Couchbase documentation

I will present how to configure your Spring Boot application to use Couchbase database server. I am assuming, that you already have Couchbase installed. If not, then you can find a download link here.

Below is the dependencies section in basic Maven configuration:


As you can see we are adding dependencies for Spring Boot, Spring Web and Spring Data Couchbase. That should be enough to write a simple web application with Couchbase used as a persistence layer. Another thing needed will be the Couchbase configuration in the Spring context. We will use Java classes configuration approach:

As you can see, four things have been configured:
  1. getBootstrapHosts() - names of hosts or IP addresses to bootstrap from.
  2. getBucketName() - name of the bucket to connect to. Bucket is a place where Couchbase stores items. It is as a logical collection of documents.
  3. getBucketPassword() - password of the bucket.
  4. getUsername() - user of the bucket.
As you can also notice, in the configuration class there is an @EnableCouchbaseRepositories annotation. It activates Couchbase repositories.


Couchbase document representation

In the NoSQL database we are relaxing the database schema and constraints. The responsibility of defining what we are expecting to receive in data retrieved from database is moved to the application layer. We can define POJO classes that can be used as a document representation. Lets have look at the example:

As you have probably noticed that is pretty similar to the entity representation of table row in JPA. Our Airline class is annotated as @Document. It is an indication for Couchbase to treat it as a representation of document stored in database. It is an equivalent of @Entity annotation used in Spring Data JPA.

There are also annotations over fields:
  1. @Id - represents an unique key of the document. It must always be present since every document in Couchbase has its unique identifier. 
  2. @GeneratedValue - unique keys with this annotation will be generated automaticaly. UNIQUE strategy means that a UUID indentifier will be generated as unique key. It is however recommended only for development-related purposes. There is also another strategy - USE_ATTRIBUTES, which combines properly annotated (with @IdAttribute) document fields to generate unique key. 
  3. @Field - it is used to mark fields in the document class that have a corresponding field in the document stored in the database.
  4. @NotNull - marks field as not null, which will prevent saving document without providing value for that field.

Couchbase repositories

After configuring Couchbase we can start writing DAO layer. It can be done in a similar way as it is done in case of relational databases - with Spring Data repositories. When creating new repository interface we can extend existing Spring Data interfaces: CrudRepository or plain Repository. There is also a CouchbasePagingAndSortingRepository which contains support for CRUD operations and also paging and sorting. All the mentioned interfaces are underneath implemented by Spring Data Couchbase repository class N1qLCouchbaseRepository.

Lets have a look at following example:


In this case we are extending CouchbasePagingAndSortingRepository. There is one method defined - findUSAirlinesByNameLike. As you can see, we are using a @Query annotation to define how should the airline data be retrieved. Thats the same approach as in the Spring Data repositories used to access relational database items. However the content of the annotation differs. Its syntax is specific for Couchbase. It is used to define queries in N1QL language. N1QL language is created by Couchbase authors and it is a superset of SQL, however it is adapted to deal with NoSQL document database. It simplifies querying database in great deal. To learn more about N1QL you can visit the following page: N1QL Language Reference. In the presented example we are selecting all the airlines from United States that have a name like the one provided in parameter. You can also define queries using query derivation from method name strategy which is widely used in Spring Data repositories, also in case of JPA. Here is the extended example of AirlinesRepository with additional method findByCallsign:

In case of findByCallsign method, query is generated based on the method's name. Spring Data Couchbase will generate a N1QL query with a WHERE condition on the 'callsign' field. Query derivation from method name is very handy when defining simple queries. On the other hand @Query annotation is a good choice when defining more complicated queries or queries that are simply not possible to be defined using method's name.

Lets have a look how AirlinesRepository  is used in Spring Controller:

Nothing complicated here. AirlinesRepository is autowired in the controller and is used in the endpoint method. REST controller with underlying relational database could look exactly the same.

Summary

We have had a a brief look at how you can configure Couchbase in Spring. We have looked how can we represent documents using Java classes. We have also seen examples of repositories used to retrieve Couchbase data. As you must have noticed, Spring Boot and Spring Data provide some abstraction layers which make usage of Couchbase pretty easy - similarly as in relational databases case. Don't forget however that there is a multitude of things to learn regarding Couchbase with Spring. If you want to expand your knowledge, then please have a look at the official documentation - Spring Couchbase documentation. .

Komentarze

Popularne posty z tego bloga

Spring Data 1# - how repositories work under the hood

PostgreSQL transactions behind the scenes - MVCC, locks, isolation levels

Hibernate 2# - physical vs logical transactions