Social Icons

Pages

Wednesday, March 12, 2014

Introduction to NoSQL and how to integrate with Spring Framework

Overview

NoSQL

What are the benefits of “NoSQL” data store over traditional “Relational Database”?

Most of people who never heard of the term “NoSQL” could really wonder about why this young technology will play an important role in the near future and lot of questions might be pop up in their head??
Database’s Table and its constraints would not make a lot of sense in using “NoSQL” technology. Due to the fact that, there are different types of “NoSQL” database storage,
  • Graph: when we want to store highly interconnected data e.g. social connection.
  • Document: when we want to store tree and variety of data structures.
  • Key /Value: when we want cache any functionality or access pattern.
When compared to the “Traditional RDBMS”“NoSQL” database is more scalable and provide good performance, and also better support in data model than the traditional one.

“NoSQL” is designed to support “Large Volumes of Structured, Semi-Structured and unstructured data” , “Agile sprints, quick iteration and frequent code pushes, Object-oriented programming, Efficient, scale-out architecture instead of expensive , monolithic architecture”

Spring Data

The Spring Data project was coined at Spring One 2010 and originated from a hacking
session of Rod Johnson (SpringSource) and Emil Eifrem (Neo Technologies) early that
year.

Why should we use the “Spring Data”?

“Spring Data provides a familiar and consistent Spring-based programming model for “NoSQL” and relational stores while retaining store-specific features and capabilities.”

The source code example can be downloaded here

Step By Step Tutorial

Step 1, Installation

We will use "MongoDB" as a document storage for this post  (MongoDB stores the data in BSON, a binary derivative of JSON)

You need to download "MongoDB" as you will need it as your "NoSQL" database for this tutorial. The latest version can be downloaded here!

Setting up "MongoDB",  you need to create a folder to contain the data for "MongoDB" (e.g  C:\app\mongodb\data)

 Starting our database server ..
. 
"mongod --dbpah C;\app\mongodb\db" 



Starting "MongoDB" shell ....

"mongo"




I will not mention much about 'MongoDB' commands. For more information please visit MongoDB Shell Reference.

Basically, you will need to know some basic commands to create our sample data for this tutorial..

To whom it may familiar with traditional database ..You can simply compare between RDBMS and NoSQL as the table below.

RDBMS
NoSQL
Table Collection
Row Document
Column Field


Basic command that we should know...

  • Show current status : 'db.stats()'
             
  • Create new database if does not exist and Use it : 'use <database name>'

  • Show all databases : "show dbs"

  • Updates an existing document (row) or inserts a new document (row) to the collection (Table) :  'db.<collection>.save({ <document>})'
    • db.customers.save({ firstname : 'Tony', lastname : 'Carter', emailAddress : 'tonycarter@kovitad.com' })

  • Find All data in the collection (Table) : 'db.<collection>.find()'


  • Find the data with basic criteria : 'db.<collection>'.find(<criteria>)'



Step 2, Adding Maven dependency...

This post applied to ...
  • Core Spring Version : 3.2.7.RELEASE
  • Spring Data MongoDB Version : 1.0.0.RELEASE
  • Mongo DB Java Driver Version : 2.7.2
  • Query DSL Version : 3.3.1




 org.springframework
 spring-core
 ${spring.core.version}


 org.springframework
 spring-web
 ${spring.core.version}


 org.springframework
 spring-context
 ${spring.core.version}


 org.springframework
 spring-tx
 ${spring.core.version}




 org.springframework.data
 spring-data-mongodb
 ${spring.data.mongodb.version}
 jar
 compile




 org.mongodb
 mongo-java-driver
 ${mongodb.driver.version}
 jar
 compile




 com.mysema.querydsl
 querydsl-core
 ${query.dsl.version}



 com.mysema.querydsl
 querydsl-mongodb
 ${query.dsl.version}


Step 3, Setting Up Domain Model


Mapping your 'POJO ' with 'NoSQL' document structure

For example, 'Customer Domain'
  • The collection name : 'customers'
    • There are three fields : 'fistname' , 'lastname' and 'emailAddress'
    • 'MongoDB' supports Index as same as the traditional 'RDBMS'.  In this example, we will regularly retrieve customer's information using the email address and it need to be unique. As the result of this, you can specify the index using this annotation : @Indexed(unique=true)
package com.kovitad.domain;

import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

/**
 * @author KOVITAD TONY JANLAKHON
 * 
 * 
 * 
Document Example :

{ 
  firstname : "Tony",
  lastname : "Carter",
  emailAddress : "tonycarter@kovitad.com" 
}
 * 
 *
 */

@Document(collection="customers")
public class Customer {
 
 @Field("firstname")
 private String firstName;
 
 @Field("lastname")
 private String lastName;
 
 @Indexed(unique=true)
 @Field("emailAddress")
 private String emailAddress;
 
}



Step 4, Implementing MongoDB Repository

Spring Data provides the tool to support simple CRUD operations
As you can see, we have a standard Spring component annotated with @Repository to make the class discoverable by classpath scanning.

package com.kovitad.repository;

import org.springframework.data.repository.Repository;
import com.kovitad.domain.Customer;


public interface CustomerRepository extends RepositoryRepository <Customer, Long> {

 Customer save(Customer customer);

 Customer findByEmailAddress(String emailAddress);
}

package com.kovitad.repository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;
import org.springframework.data.mongodb.core.query.Query;
import com.kovitad.domain.Customer;

@Repository
public class MongoDBCustomerRepository implements CustomerRepository {

 private final MongoOperations operations;

 @Autowired
 public MongoDBCustomerRepository(final MongoOperations operations) {
  Assert.notNull(operations);
  this.operations = operations;
 }

 @Override
 public Customer save(Customer customer) {
  operations.save(customer);;
  return customer;
 }

 @Override
 public Customer findByEmailAddress(String emailAddress) {
  Query query = query(where("emailAddress").is(emailAddress));
  return operations.findOne(query, Customer.class);
 }

}


Step 5, Embedding Data Model And MongoDB Repository with Spring Framework

You can set up MongoDB infrastructure using either XML or Java Configuration
Setting Up "MongoDB" infrastructure using 'XML' configuration


 
 
  
  
 
 



Setting Up "MongoDB" infrastructure using 'Java' Configuration
package com.kovitad.repository.configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import com.mongodb.Mongo;
import com.mongodb.WriteConcern;

@Configuration
public class ApplicationConfig extends AbstractMongoConfiguration{

 @Override
 public String getDatabaseName() {
  return "e-shop";
 }

 @Override
 public Mongo mongo() throws Exception {
  Mongo mongo = new Mongo();
  mongo.setWriteConcern(WriteConcern.SAFE);
  return mongo;
 }
 @Override
 public String getMappingBasePackage() {
   return "com.kovitad.domain";
 }
}




To be continue!







No comments:

Post a Comment

 
Blogger Templates