Configuring Apache Drill with MongoDB on Windows

Hi All, first of all “A very Happy New Year” to every one. Today we are doing to an awesome tool “Apache Drill” which is made to query any NoSql Database if the form of tables even though the tables does not exist. With ‘Drill’ we can start querying any non relational database just like relational database. Apache Drill supports almost all NoSql databases and filesystems like HBase, Hadoop File System, MongoDB, Hive, MapR-DB and Amazon-S3 and many more.
We start trating our JSON data just like table data event when its not.
Drill features a JSON data model that enables queries on complex/nested data as well as rapidly evolving structures commonly seen in modern applications and non-relational datastores. Drill also provides intuitive extensions to SQL so that you can easily query complex data.(credits Apache Drill page.)

any-db

Now let us see how to install Apache Drill on you local machine and how to configure it with MongoDB.
1. Download and install Apache Drill from here
2. Download MongoDB from here

once downloaded and installed both of the software, we shall start Apache Drill first.

Step1 : Navigate to /bin/ in command prompt

Step2 : now type the following command sqlline.bat -u “jdbc:drill:zk=local”

your Apache drill should start with out any errors as shown below.
drill-shell

once the Apache drill server is up and running then start the Web Console by hitting the following url.
Step3 : http://localhost:8047/

once you have the web console ready, please go to storage menu and enable mongodb plugin by putting the following content. ensure your mongodb server is up and running before this step is done.
{
“type”: “mongo”,
“connection”: “mongodb://localhost:27017/”,
“enabled”: true
}

once done we can start querying the mongodb same as relational database as shown below.
query-window
query-results

The same results in mongodb client shell as shown below.
mongodb-shell-results

Thats all folks, you have successfully configured Apache Drill with mongoDB. in my next post will be integrating Apache drill to Java and query MongoDB.

Happy Drilling 🙂

Aspect Oriented Programming – Advices

Aspect oriented Programming is a cross cutting concepts to OOP. AOP in Spring is used in replacement to EJB for it’s declarative programming style. in this tutorial we will look into different advices that AspectJ supports in Spring.

First of all an Advice is a functionality that we want to execute before or after some method is getting executed.
There are 4 types of Advices that Spring Supports.

  • BeforeAdvice : this advice is executed before every method call
  • AfterAdvice : this advice is executed after every method call. please note that this will not get executed if a method throws some exception
  • AfterThrowingAdvice : this advice is executed after every method throws some configured exceptions
  • AroundAdvice : this advice is executed before and after every method call

let us dive directly to code part as the above explanation is straight forward.
Step1: Let us look into POM.xml file

<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.spark.aop</groupId>
	<artifactId>AOPTutorial</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>AOPTutorial</name>
	<description>AOPTutorial</description>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.8.5</version>
		</dependency>
		<dependency>
			<groupId>aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.5.4</version>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>3.1</version>
		</dependency>
	</dependencies>

	<properties>
		<spring.version>4.1.8.RELEASE</spring.version>
	</properties>
</project>

Step2: let us look into our application-context.xml file, which acts as the spring configuration file.

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">

	<bean id="customerService" class="com.spark.aop.service.CustomerService">
		<property name="customerId" value="10"></property>
	</bean>

	<bean id="beforeAdvice" class="com.spark.aop.advice.BeforeAdvice" />
	<bean id="afterAdvice" class="com.spark.aop.advice.AfterAdvice" />
	<bean id="throwAdvice" class="com.spark.aop.advice.ThrowAdvice" />

	<bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">

		<property name="target" ref="customerService" />

		<property name="interceptorNames">
			<list>
				<value>beforeAdvice</value>
				<value>afterAdvice</value>
				<value>throwAdvice</value>
			</list>
		</property>
	</bean>
</beans>

now let us start writing the classes that were shown in the above configuration file.
Step3: write a class named BeforeAdvice.java which will implement MethodBeforeAdvice.java interface. this interface has before method which gets executed before every method call

package com.spark.aop.advice;

import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;

/**
 * @author Sony
 *
 */
public class BeforeAdvice implements MethodBeforeAdvice {
	public void before(Method method, Object[] args, Object target) throws Throwable {
		System.out.println("BeforeAdvice class : Before method !");
	}
}

Step4: Now let us write the service class as shown below, which has got some specific operations to be done.

/**
 * 
 */
package com.spark.aop.service;

/**
 * @author Sony
 *
 */
public class CustomerService {

	private int customerId;

	public int getCustomerId() {
		return customerId;
	}

	public void setCustomerId(int customerId) {
		this.customerId = customerId;
	}

	public void getCustomerById() {
		System.out.println("******* CustomerService*********"+customerId);
	}
	
	public void getException() throws IllegalArgumentException {
		 throw new IllegalArgumentException();
	}
}

Step5: finally let us code our main program through which we can start test our advice functionality.

package com.spark.aop.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spark.aop.service.CustomerService;

public class App {
	public static void main(String[] args) {
		ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] { "application-context.xml" });

		CustomerService cust = (CustomerService) appContext.getBean("customerServiceProxy");

		System.out.println("************Main Method*************");
		cust.getCustomerById();
		System.out.println("************Going to throw Exception*************");
		try {
			cust.getException();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		
	}
}

Misc : the code for AfterAdvice.java and ThrowAdvice.java are given below.

/**
 * 
 */
package com.spark.aop.advice;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;

/**
 * @author Sony
 *
 */
public class AfterAdvice implements AfterReturningAdvice {

	public void afterReturning(Object object, Method method, Object[] objects, Object object2) throws Throwable {
		
		System.out.println("AfterAdvice class : After method !");
	}

}

/**
 * 
 */
package com.spark.aop.advice;

import org.springframework.aop.ThrowsAdvice;

/**
 * @author Sony
 *
 */
public class ThrowAdvice implements ThrowsAdvice{

	public void afterThrowing(IllegalArgumentException e) throws Throwable {
		System.out.println("ThrowAdvice class : Method Thrown exception !");
	}
}

That’s it guys we have finished coding advices in spring.
practical scenario : this kind of approach is very much useful while writing logging facility in projects.
please test the code on your own, and let me know if anything is needed.

Happy Advices 🙂

Using SpringBoot , SpringData and MongoDB

Hello everybody, its a long gap that i have not written a post in my blog. This post could be my last post in 2015. today we are going to see how to integrate Spring’s one of the best feature Spring Boot with Spring data and MongoDB.

Spring Boot:(courtesy Spring.io) Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”. Most Spring Boot applications need very little Spring configuration.


Features:

  • Create stand-alone Spring applications
  • Embed Tomcat, Jetty
  • Automatically configure Spring whenever possible
  • Absolutely no code generation and no requirement for XML configuration

Now let us create a project that can integrate the above mentioned technology stack.
spring-boot-proj

Step 1: create the mongo-db.properties file in src/main/resources folder

MONGO_DB_HOST=127.0.0.1
MONGO_DB_PORT=27017
DB=school

Step 2: create the application configuration java class which is responsible for creating the MongoTemplate object. below is AppConfig.java

/**
 * 
 */
package com.spark.spring.practice.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;

/**
 * @author Sony
 *
 */
@Configuration
@PropertySource(value = "classpath:mongo-config.properties")
public class AppConfig {

	@Value("${MONGO_DB_HOST}")
	private String MONGO_DB_HOST;

	@Value("${MONGO_DB_PORT}")
	private int MONGO_DB_PORT;

	@Value("${DB}")
	private String DB;

	protected String getDatabaseName() {
		return DB;
	}

	@Bean
	public Mongo getMongo() throws Exception {
		return new MongoClient(MONGO_DB_HOST, MONGO_DB_PORT);
	}

	@Bean
	public MongoDbFactory mongoDbFactory() throws Exception {
		return new SimpleMongoDbFactory(getMongo(), getDatabaseName());
	}

	@Bean
	public MongoTemplate mongoTemplate() throws Exception {

		MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());

		return mongoTemplate;

	}
}

Step 3: create the pojo classes which are mapped as documents in mongodb. below are the Student.java and Score.java respectively

/**
 * 
 */
package com.spark.spring.practice.beans;

import java.util.List;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

/**
 * @author Sony
 *
 */
@Document(collection = "students")
public class Student {

	@Id
	private int _id;
	@Field(value="name")
	private String name;
	@Field(value="scores")
	List<Score> scores;

	public int get_id() {
		return _id;
	}

	public void set_id(int _id) {
		this._id = _id;
	}

	public String getName() {
		return name;
	}

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

	public List<Score> getScores() {
		return scores;
	}

	public void setScores(List<Score> scores) {
		this.scores = scores;
	}

}

/**
 * 
 */
package com.spark.spring.practice.beans;

/**
 * @author Sony
 *
 */
public class Score {

	private String type;
	private double score;

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public double getScore() {
		return score;
	}

	public void setScore(double score) {
		this.score = score;
	}

}

Step 4: create the controller class which can handle the request coming from client. in this example the controller is called GlobalController.java. The controller class is autowired with MongoTemplate Object and StudentRepository, so let us create StudentRepository so that it will get injected into the controller, when the class loads to spring container. MongoTemplate is readily configured in the AppConfig.java file.

/**
 * 
 */
package com.spark.spring.practice.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.spark.spring.practice.beans.Student;
import com.spark.spring.practice.repositories.StudentRepository;

/**
 * @author Sony
 *
 */
@RestController
@RequestMapping(value = "/rest/v1/students")
public class GlobalController {
	
	Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private MongoTemplate mongoTemplate;
	
	@Autowired
	private StudentRepository studentRepository;

	@RequestMapping(value = "/findall", method = RequestMethod.GET)
	public List<Student> getAllStudents() {
		List<Student> students = studentRepository.findAll();
		return students;
	}
}

Step 5: create the repository interface which will extend the MongRepository<T,ID> interface from spring library.

/**
 * 
 */
package com.spark.spring.practice.repositories;

import org.springframework.data.mongodb.repository.MongoRepository;

import com.spark.spring.practice.beans.Student;

/**
 * @author Sony
 *
 */
public interface StudentRepository extends MongoRepository<Student, Integer> {

}

Step 6: create the main class which will act as booting mechanism and will start the project with the help of @SpringBootApplication & @EnableMongoRepositories annotations

/**
 * 
 */
package com.spark.spring.practice.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

/**
 * @author Sony
 *
 */
@SpringBootApplication
@ComponentScan(basePackages={"com.spark.spring.practice"})
@EnableMongoRepositories(basePackages={"com.spark.spring.practice"})
public class SpringBootMain {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		SpringApplication.run(SpringBootMain.class, args);
	}

}

that’s all guys we are done with coding part. Its time for us to run the project. once you ran the project with out errors then below is the kind of output that can be seen on console.
Spring-boot-console

now open the REST-client add-on either in chrome or firefox and test your services.
Happy Spring-booting 🙂

Configuring Multi Node Cassandra Cluster on Windows Machine.

Hi All, These days we hear a lot of buzz in and around the IT industry regarding the BigData and NoSql. Here in this post i wanted to show you how to setup multi node cluster on single machine(Windows).

In Windows machine please navigate to “C:\Windows\System32\drivers\etc” and edit the “hosts.etc” file and add the following content as below.

#cassandra cluster nodes
127.0.0.1 127.0.0.2 
127.0.0.1 127.0.0.3 
127.0.0.1 127.0.0.4 
127.0.0.1 127.0.0.5 
127.0.0.1 127.0.0.6 

once we add the cassandra nodes to hosts.etc file, please download the latest version of Apache Cassandra from the following sitedownload cassandra once downloaded please extract that to one of the folders as “appache-cassandra-2.1.6-node1″(similarly, extract 3 different copies of the same zip file to 3 different folders).

once you are ready with Cassandra folders now its time to modify the cassandra config file located in /conf/cassandra.yaml file.
please edit the following values in the config file

cluster_name: 'DemoCluster'

Provide the seed nodes for each cassandra.yaml file as 127.0.0.1 and 127.0.0.2 etc.;

seed_provider: # Addresses of hosts that are deemed contact points. 
# Cassandra nodes use this list of hosts to find each other and learn 
# the topology of the ring. You must change this if you are running 
# multiple nodes! - class_name: org.apache.cassandra.locator.SimpleSeedProvider parameters: 
# seeds is actually a comma-delimited list of addresses. 
# Ex: "<ip1>,<ip2>,<ip3>" 
- seeds: "127.0.0.1,127.0.0.2"

Note: You need to ensure that the following values are changed for each node
directories where Cassandra should store data on disk

data_file_directories: - /training/node1/var/lib/cassandra/data 

# commit log 
commitlog_directory: /training/node1/var/lib/cassandra/commitlog 

# saved caches 
saved_caches_directory: /training/node1/var/lib/cassandra/saved_caches

make sure you also change the follwing listen address and rpc address for every node of cassandra.

listen_address: 127.0.0.1 
rpc_address: 127.0.0.1

finally your configuration should look as
Node 1 = 127.0.0.1
Node 2 = 127.0.0.2
Node 3 = 127.0.0.3
Node 4 = 127.0.0.4
Node 5 = 127.0.0.5

Thats it, we have configured the multi node cassandra cluster and its ready to run.
Please post me if you face any problem in the configuration and setup related issues.

Happy Configuring Cassandra. 🙂

Spring Data Rest + AngularJS + MongoDB

Hello everybody, this time i took little long time to post an article here. Here i came up with a very powerful integration pack called “Integration of Spring data rest with AngularJS and MongoDB”. Now a days this combination is best suited for SPA – “Single Page Application” with light weight back end support with mongodb. Now we will have a Jump start into the tutorial. this tutorial will assume the prior basic knowledge of

  • Java8
  • Spring & Spring Data Rest
  • MongoDB

the project structure looks as below.
SpringAngularJSProj

Before proceeding with the Spring integration with angularjs and mongodb, please install mongodb and start the mongodb server. if everything goes well server startup should look as below.
mongodb_server_start

Now install any GUI client for mongodb for easy access, we can even access mongodb with out client but this is for better user experience. I personally use “Robomongo” and once you connect Robomongo to MongoDB server that will look as below.
robomongo

Once everything is ready and inplace, let us start with writing the code. I have used Maven to manage the dependencies and hence the pom.xml looks as below.

<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.spark.ng.spring</groupId>
	<artifactId>AngularSpring</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>AngularSpring</name>
	<description>AngularSpring</description>

	<properties>
		<spring-version>4.1.2.RELEASE</spring-version>
		<jdk-version>1.8</jdk-version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring-version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring-version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring-version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring-version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring-version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-rest-core</artifactId>
			<version>2.3.0.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-mongodb</artifactId>
			<version>1.5.2.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-rest-webmvc</artifactId>
			<version>2.3.0.RELEASE</version>
		</dependency>

		<!-- mongodb java driver -->
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>2.11.0</version>
		</dependency>
		
		<!-- Servlet 3.x api -->
		 <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>
        
	</dependencies>

	<build>
		<finalName>AngularSpring</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.4</version>
				<configuration>
					<warSourceDirectory>src/main/webapp</warSourceDirectory>
					<warName>AngularSpring</warName>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Once the dependencies are downloaded let us start with the configuration. In this tutorial i am moving with NoXml style of configuration.
ApplicationConfig.java

/**
 * 
 */
package com.spark.ng.spring.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import com.mongodb.MongoClient;

/**
 * @author Mantha Pavan Kumar
 *
 */
@Configuration
@EnableWebMvc
@ComponentScan(basePackages={"com.spark.ng.spring"})
@EnableMongoRepositories(basePackages={"com.spark.ng.spring.data.repository"})
@Import(RepositoryRestMvcConfiguration.class)
public class ApplicationConfig {
	
	public @Bean
    MongoDbFactory mongoDbFactory() throws Exception {
		MongoClient mongoClient = new MongoClient("localhost",27017);
        return new SimpleMongoDbFactory(mongoClient, "Customer");
    }

    public @Bean
    MongoTemplate mongoTemplate() throws Exception {
        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
        return mongoTemplate;
    }
    
	@Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".html");
 
        return viewResolver;
    }
}

WebApplicationConfig.java

/**
 * 
 */
package com.spark.ng.spring.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * @author Mantha Pavan Kumar
 *
 */
public class WebApplicationConfig implements WebApplicationInitializer{

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		
		AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext = new AnnotationConfigWebApplicationContext();
		annotationConfigWebApplicationContext.register(ApplicationConfig.class);
		annotationConfigWebApplicationContext.setServletContext(servletContext);
		
		ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(annotationConfigWebApplicationContext));
		servlet.setLoadOnStartup(1);
		servlet.addMapping("/rest/*");
	}

}

With the above two files we are done with the configuration part. Let us talk about ApplicationConfig.java a little more in deep. At the top of the class please take a close look, i have annotated the class with “@EnableWebMvc”, which will enable all “@Component” based class and scans them when the application is loaded by the web container. The annotation “@EnableWebMvc” is equivalent to “”. Moving little forward “@ComponentScan” will scan all the @Component based classes. Now comes the “@EnableMongoRepositories” which will load all the repositories. Finally we have imported a core class from the Spring API called “RepositoryRestMvcConfiguration” this is the class responsible for converting the domain objects back and forth to JSON format and acts as a communication bridge between clint(browser) & backend. In this class we have innitialised two beans called “MongoDBFactory” & “MongoTemplate” since if we have any operation to do apart from Repository implementation then we can use of “MongoTemplate” object to fulfill that.

Let us have a look at the domain object Customer.java

/**
 * 
 */
package com.spark.ng.spring.domain.objects;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;


/**
 * @author PavanKumar Mantha
 *
 */
@Document(collection="customer")
public class Customer {

	@Id
	@Field
	private String id;
	@Field
	private String customerId;
	@Field
	private String firstName;
	@Field
	private String lastName;
	@Field
	private String contactAddr;
	@Field
	private String mobileNumber;
	

	/**
	 * @return the customerId
	 */
	public String getCustomerId() {
		return customerId;
	}

	/**
	 * @param customerId
	 *            the customerId to set
	 */
	public void setCustomerId(String customerId) {
		this.customerId = customerId;
	}

	/**
	 * @return the firstName
	 */
	public String getFirstName() {
		return firstName;
	}

	/**
	 * @param firstName
	 *            the firstName to set
	 */
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	/**
	 * @return the lastName
	 */
	public String getLastName() {
		return lastName;
	}

	/**
	 * @param lastName
	 *            the lastName to set
	 */
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	/**
	 * @return the contactAddr
	 */
	public String getContactAddr() {
		return contactAddr;
	}

	/**
	 * @param contactAddr
	 *            the contactAddr to set
	 */
	public void setContactAddr(String contactAddr) {
		this.contactAddr = contactAddr;
	}

	/**
	 * @return the mobileNumber
	 */
	public String getMobileNumber() {
		return mobileNumber;
	}

	/**
	 * @param mobileNumber
	 *            the mobileNumber to set
	 */
	public void setMobileNumber(String mobileNumber) {
		this.mobileNumber = mobileNumber;
	}

}

A generic Response object with which we can send messages back to browser.

/**
 * 
 */
package com.spark.ng.spring.domain.objects;

/**
 * @author Sony
 *
 */
public class ResponseObject {

	private String message;

	/**
	 * @return the message
	 */
	public String getMessage() {
		return message;
	}

	/**
	 * @param message
	 *            the message to set
	 */
	public void setMessage(String message) {
		this.message = message;
	}

}

The class “ApplicationRepositoryUtil.java will get us all the objects that are required using the @Autowired annotation.

/**
 * 
 */
package com.spark.ng.spring.data.repository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

/**
 * @author Sony
 *
 */
@Service
public class ApplicationRepositoryUtil {

	@Autowired
	private MongoTemplate mongoTemplate;
	@Autowired
	private CustomerRepository customerRepository;

	/**
	 * @return the mongoTemplate
	 */
	public MongoTemplate getMongoTemplate() {
		return mongoTemplate;
	}

	/**
	 * @return the customerRepository
	 */
	public CustomerRepository getCustomerRepository() {
		return customerRepository;
	}

}

Here comes the exact repository that we were talking from little while. Please observe the repository carefully. Its an interface extending one more interface called “MongoRepository”.The goal of Spring Data repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores.The central interface in Spring Data repository abstraction is Repository (probably not that much of a surprise). It takes the domain class to manage as well as the id type of the domain class as type arguments. This interface acts primarily as a marker interface to capture the types to work with and to help you to discover interfaces that extend this one. The CrudRepository provides sophisticated CRUD functionality for the entity class that is being managed. MongoRepository extends the basic CrudRepository.

/**
 * 
 */
package com.spark.ng.spring.data.repository;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import com.spark.ng.spring.domain.objects.Customer;

/**
 * @author Sony
 *
 */
@RepositoryRestResource(collectionResourceRel="customer",path="customer")
public interface CustomerRepository extends MongoRepository<Customer, Integer> {

}

Here is a simple controller that will receive the requests from clients and delegates them to appropriate layers.

/**
 * 
 */
package com.spark.ng.spring.controller;

import java.util.function.Supplier;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.spark.ng.spring.data.repository.ApplicationRepositoryUtil;
import com.spark.ng.spring.domain.objects.ResponseObject;

/**
 * @author Sony
 *
 */
@RestController
@RequestMapping(value = "/app")
public class ApplicationController {

	@Autowired
	ApplicationRepositoryUtil applicationRepositoryUtil;

	@RequestMapping("/test")
	public ResponseObject handleRequest() {
		System.out
				.println("---------------------Testing method called---------------- Mongo Template :"
						+ applicationRepositoryUtil.getMongoTemplate()
						+ " Repository Object : "
						+ applicationRepositoryUtil.getCustomerRepository());
		Supplier<ResponseObject> supplier = ResponseObject::new;
		ResponseObject responseObject = supplier.get();

		responseObject.setMessage("Sample Data Object");
		return responseObject;

	}
}

Now we done with the java part and now its time for us to write the Html and java script. please download latest AngularJS library and include the “angular.min.js” inside your project, after including please write a file called “mongo.module.js” and out the following content into it.

/**
 * 
 */
var myApp = angular.module('myApp', ['controllers']);

Now write an AngularJs controller which is responsible for firing the Ajax request to the Spring and get the data in REST format. create a folder called “controllers” and create a file “controllers.js” and put the following content into it.

/**
 * 
 */

var controllersModule = angular.module('controllers', []);

controllersModule.controller('SampleController', function($scope) {
	console.log('Sample Load done !');
});

controllersModule.controller('ajaxController', function($scope, $http) {
	$http.get('/AngularSpring/rest/customer/').success(function(data) {
		console.log(data);
	});
});

Let us create an Html file “index.html” with the below content

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="ISO-8859-1">
<title>Index Page</title>
<script type="text/javascript" src="jsLib/angular.min.js"></script>
</head>
<body>
	<div ng-controller="SampleController">Hello AngularJs</div>
	<div ng-controller="ajaxController">Hello Spring Data Rest & MongoDB</div>

</body>
<script type="text/javascript" src="mongo.module.js"></script>
<script type="text/javascript" src="controllers/controllers.js"></script>
</html>

That is it guys we are done from coding part and its time for us to build the application and deploy it to server.
Once we deploy the application into the server, please install an Add on to firefox or chrome called “RESTClient” from which we can test our repositories are working or not.
RestClient

Once you fire the request as shown in the above screen shot, we should get the response from the service as below.
REST_Response

Now try to open our page “index.html” and in firebug console we could see the same response as above which means pur angularjs is firing the request and our Spring repositories are responding to the request.

index

Happy Spring Data REst + AngularJS + MongoDB 🙂
Happy Coding 🙂

Oracle Fusion Middleware – “How to Query Oracle Coherence” ?

In my previous post “Oracle Fusion Middleware – Concepts of Oracle Coherence” i have explained how to preLoad cache which means get all the required details for the first time and put that into cache. Today i am going to explain how to query the cache once we have the details.

Querying in Oracle Coherence is obtained by set of Filters that the Coherence has provided us. Please be noted that queries apply only to currently cached data thus, the data set should be loaded entirely into cache before queries are performed(go through my preLoading concept in the previous post).

The concept of querying is based on the ValueExtractor interface. A value extractor is used to extract an attribute from a given object for querying Most developers need only the ReflectionExtractor implementation of this interface. The implementation uses reflection to extract an attribute from a value object by referring to a method name which is typically a getter method

Let me show you the example which is connected to my previous post:

/**
 * 
 */
package com.spark.coherence.cache.filters;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.spark.coherence.cache.repository.CacheRepository;
import com.spark.coherence.pof.beans.EmployeeBean;
import com.tangosol.util.Filter;
import com.tangosol.util.ValueExtractor;
import com.tangosol.util.extractor.ReflectionExtractor;
import com.tangosol.util.filter.EqualsFilter;
import com.tangosol.util.filter.GreaterEqualsFilter;
import com.tangosol.util.filter.GreaterFilter;

/**
 * @author Sony
 *
 */
public class EmployeeFilter {

	ValueExtractor valueExtractor;

	@SuppressWarnings("rawtypes")
	public EmployeeBean equalsFilter(String methodName, String methodParam) {
		valueExtractor = new ReflectionExtractor(methodName);
		Filter filter = new EqualsFilter(valueExtractor, methodParam);
		EmployeeBean person = null;
		for (Iterator iter = CacheRepository.getEmployeeCache().entrySet(filter).iterator(); iter.hasNext();) {
			Map.Entry entry = (Map.Entry) iter.next();
			Integer key = (Integer) entry.getKey();
			person = (EmployeeBean) entry.getValue();
		}
		return person;
	}
	
	@SuppressWarnings("rawtypes")
	public List<EmployeeBean> greaterThanFilter(String methodName, int methodParam) {
		valueExtractor = new ReflectionExtractor(methodName);
		Filter filter = new GreaterEqualsFilter(valueExtractor, methodParam);
		List<EmployeeBean> employeeBeans = new ArrayList<>();
		for (Iterator iter = CacheRepository.getEmployeeCache().entrySet(filter).iterator(); iter.hasNext();) {
			Map.Entry entry = (Map.Entry) iter.next();
			Integer key = (Integer) entry.getKey();
			EmployeeBean person = (EmployeeBean) entry.getValue();
			employeeBeans.add(person);
		}
		return employeeBeans;
	}

}

Happy Caching..Happy Coding 🙂

Integrating Spring with MongoDB

Hi all from past few weeks i was doing research on NoSql, so in the research i found that NoSql has been categorized into three types “Document Database”,”Column Database”,”Graph Based Database”. I have chose two database to integrate with spring one is MongoDB(Document based database) and the other is Apache Cassandra (Column Family Database). In this post i am going to explain how to integrate MongoDB with Spring. In later posts i will explain how to integrate Spring with Cassandra.

Note : before start reading this post please install MongoDB, based on your OS compatibility.

Let us talk about mongodb a little bit before we dive into the tutorial.
MongoDB is cross-platform document oriented database that provide high reliability and scalability, this works on concepts of documents and collections.

A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection’s documents may hold different types of data.

A collection is set of documents, this collection can exist in single or multi-node cluster database. A document with in a collection can have different fields.

the project structure looks as below.
mongo-proj-struct

let us see the pom.xml configuration. This project is compatible with java 8 specification.
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.spark.springdata.mongodb</groupId>
	<artifactId>SpringDataMongoDB</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringDataMongoDB</name>
	<description>SpringDataMongoDB</description>

	<properties>
		<spring-version>3.2.8.RELEASE</spring-version>
	</properties>

	<!-- Spring framework -->

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring-version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring-version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring-version}</version>
		</dependency>

		<!-- mongodb java driver -->
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>2.11.0</version>
		</dependency>

		<!-- Spring data mongodb -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-mongodb</artifactId>
			<version>1.2.0.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2.2</version>
		</dependency>

		<!-- oracle and mysql -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.6</version>
		</dependency>

		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc14</artifactId>
			<version>14.0.0</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.2</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

Now let us take a look at the Spring configuration file application-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cache="http://www.springframework.org/schema/cache"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
		http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.2.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">

	<context:property-placeholder location="classpath:jdbc.properties" />

	<bean id="orclDataSource" class="oracle.jdbc.pool.OracleDataSource"
		destroy-method="close">
		<property name="URL" value="${orcl.jdbc.url}" />
		<property name="user" value="${orcl.jdbc.username}" />
		<property name="password" value="${orcl.jdbc.password}" />
		<property name="connectionCachingEnabled" value="true" />
	</bean>

	<bean name="mysqlDataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${mysql.jdbc.driver}" />
		<property name="url" value="${mysql.jdbc.url}" />
		<property name="username" value="${mysql.jdbc.user}" />
		<property name="password" value="${mysql.jdbc.password}" />
	</bean>

	<context:component-scan base-package="com.spark.spring.data" />

	<!-- Factory bean that creates the Mongo instance -->
	<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
		<property name="host" value="localhost" />
	</bean>

	<!-- MongoTemplate for connecting and quering the documents in the database -->
	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
		<constructor-arg name="mongo" ref="mongo" />
		<constructor-arg name="databaseName" value="person" />
	</bean>
	
	<bean id="personService" class="com.spark.spring.data.service.PersonService">
	    <constructor-arg name="mongoTemplate" ref="mongoTemplate"/>
	</bean>
</beans>

Now let us look at the Utility class that will help us to load the configuration file and fetch the different bean objects.

/**
 * 
 */
package com.spark.spring.data.util;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;

/**
 * @author PavanKumar Mantha
 * 
 */
public class SpringDataUtil {

	private static Future<ApplicationContext> applicationContext;

	static {
		ExecutorService executorService = Executors.newFixedThreadPool(1);
		applicationContext = executorService
				.submit(new Callable<ApplicationContext>() {
					public ApplicationContext call() throws Exception {
						return new ClassPathXmlApplicationContext(
								"application-context.xml");
					}

				});
	}

	/**
	 * @return
	 */
	public static ApplicationContext getContext() {
		try {
			return applicationContext.get();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	/**
	 * @return
	 */
	public static DataSource getOracleDataSource() {
		try {
			return (DataSource) getContext().getBean("orclDataSource");
		} catch (Exception e) {
			throw new RuntimeException();
		}
	}

	/**
	 * @return
	 */
	public static DataSource getMysqleDataSource() {
		try {
			return (DataSource) getContext().getBean("mysqlDataSource");
		} catch (Exception e) {
			throw new RuntimeException();
		}
	}

	/**
	 * @param beanName
	 * @return
	 */
	public static Object getObject(String beanName) {
		return getContext().getBean(beanName);
	}

	public static MongoTemplate getMongoTemplate(){
		return (MongoTemplate) getContext().getBean("mongoTemplate");
	}
	
}

Let us create the domain objects in order to hold the data and these are the objects that gets persisted as documents inside mongodb.
Person.java

/**
 * 
 */
package com.spark.spring.data.document.obj;

import java.util.List;
import java.util.Set;

import org.springframework.data.annotation.Id;

/**
 * @author PavanKumar Mantha
 *
 */
public class Person {

	@Id
	private int id;
	private String firstName;
	private String lastName;
	private Set<String> phoneNumbers;
	private List<Address> address;

	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}

	/**
	 * @return the firstName
	 */
	public String getFirstName() {
		return firstName;
	}

	/**
	 * @param firstName
	 *            the firstName to set
	 */
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	/**
	 * @return the lastName
	 */
	public String getLastName() {
		return lastName;
	}

	/**
	 * @param lastName
	 *            the lastName to set
	 */
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	/**
	 * @return the phoneNumbers
	 */
	public Set<String> getPhoneNumbers() {
		return phoneNumbers;
	}

	/**
	 * @param phoneNumbers
	 *            the phoneNumbers to set
	 */
	public void setPhoneNumbers(Set<String> phoneNumbers) {
		this.phoneNumbers = phoneNumbers;
	}

	/**
	 * @return the address
	 */
	public List<Address> getAddress() {
		return address;
	}

	/**
	 * @param address
	 *            the address to set
	 */
	public void setAddress(List<Address> address) {
		this.address = address;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((address == null) ? 0 : address.hashCode());
		result = prime * result
				+ ((firstName == null) ? 0 : firstName.hashCode());
		result = prime * result + id;
		result = prime * result
				+ ((lastName == null) ? 0 : lastName.hashCode());
		result = prime * result
				+ ((phoneNumbers == null) ? 0 : phoneNumbers.hashCode());
		return result;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Person other = (Person) obj;
		if (address == null) {
			if (other.address != null)
				return false;
		} else if (!address.equals(other.address))
			return false;
		if (firstName == null) {
			if (other.firstName != null)
				return false;
		} else if (!firstName.equals(other.firstName))
			return false;
		if (id != other.id)
			return false;
		if (lastName == null) {
			if (other.lastName != null)
				return false;
		} else if (!lastName.equals(other.lastName))
			return false;
		if (phoneNumbers == null) {
			if (other.phoneNumbers != null)
				return false;
		} else if (!phoneNumbers.equals(other.phoneNumbers))
			return false;
		return true;
	}
	
	

}

Adddress.java

/**
 * 
 */
package com.spark.spring.data.document.obj;

import org.springframework.data.annotation.Id;

/**
 * @author Sony
 *
 */
public class Address {

	@Id
	private int id;
	private String doorNo;
	private String street;
	private String city;
	private String country;
	private String zipcode;

	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}

	/**
	 * @return the doorNo
	 */
	public String getDoorNo() {
		return doorNo;
	}

	/**
	 * @param doorNo
	 *            the doorNo to set
	 */
	public void setDoorNo(String doorNo) {
		this.doorNo = doorNo;
	}

	/**
	 * @return the street
	 */
	public String getStreet() {
		return street;
	}

	/**
	 * @param street
	 *            the street to set
	 */
	public void setStreet(String street) {
		this.street = street;
	}

	/**
	 * @return the city
	 */
	public String getCity() {
		return city;
	}

	/**
	 * @param city
	 *            the city to set
	 */
	public void setCity(String city) {
		this.city = city;
	}

	/**
	 * @return the country
	 */
	public String getCountry() {
		return country;
	}

	/**
	 * @param country
	 *            the country to set
	 */
	public void setCountry(String country) {
		this.country = country;
	}

	/**
	 * @return the zipcode
	 */
	public String getZipcode() {
		return zipcode;
	}

	/**
	 * @param zipcode
	 *            the zipcode to set
	 */
	public void setZipcode(String zipcode) {
		this.zipcode = zipcode;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((city == null) ? 0 : city.hashCode());
		result = prime * result + ((country == null) ? 0 : country.hashCode());
		result = prime * result + ((doorNo == null) ? 0 : doorNo.hashCode());
		result = prime * result + ((street == null) ? 0 : street.hashCode());
		result = prime * result + ((zipcode == null) ? 0 : zipcode.hashCode());
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Address other = (Address) obj;
		if (city == null) {
			if (other.city != null)
				return false;
		} else if (!city.equals(other.city))
			return false;
		if (country == null) {
			if (other.country != null)
				return false;
		} else if (!country.equals(other.country))
			return false;
		if (doorNo == null) {
			if (other.doorNo != null)
				return false;
		} else if (!doorNo.equals(other.doorNo))
			return false;
		if (street == null) {
			if (other.street != null)
				return false;
		} else if (!street.equals(other.street))
			return false;
		if (zipcode == null) {
			if (other.zipcode != null)
				return false;
		} else if (!zipcode.equals(other.zipcode))
			return false;
		return true;
	}

}

Once the document objects are ready in hand let us start writing the service implementation. Please observe service class the MongoTemplate (Similar to JdbcTemplate) of SpringFramework gets injected as constructor argument and this is responsible of doing different operations on database.
PersonService.java

/**
 * 
 */
package com.spark.spring.data.service;

import java.util.List;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import com.spark.spring.data.document.obj.Person;

/**
 * @author PavanKumar Mantha
 * 
 */
public class PersonService {

	private MongoTemplate mongoTemplate;
	private static final String COLLECTION_NAME = "person";

	/**
	 * @param mongoTemplate
	 */
	public PersonService(MongoTemplate mongoTemplate) {
		this.mongoTemplate = mongoTemplate;
	}
	
	public void setMongoTemplateObject(MongoTemplate mongoTemplate) {
		this.mongoTemplate = mongoTemplate;
	}

	/**
	 * @param person
	 * @return
	 */
	public boolean addPerson(Person person) {
		boolean status = false;
		try {
			if (!mongoTemplate.collectionExists(Person.class)) {
				mongoTemplate.createCollection(Person.class);
			}
			mongoTemplate.insert(person, COLLECTION_NAME);
			status = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return status;
	}

	/**
	 * @return
	 */
	public List<Person> listPerson() {
		return mongoTemplate.findAll(Person.class, COLLECTION_NAME);
	}

	/**
	 * @param person
	 */
	public void deletePerson(Person person) {
		mongoTemplate.remove(person, COLLECTION_NAME);
	}
	
	/**
	 * 
	 */
	public void deleteAll() {
		mongoTemplate.getDb().dropDatabase();
	}
	
	/**
	 * @param id
	 * @return
	 */
	public Person findPersonById(String id){
		//BasicQuery query = new BasicQuery("{Name:'"+name+"'}");
		
		Query query = new Query();
		query.addCriteria(Criteria.where("_id").is(id));
		
		Person person = mongoTemplate.findOne(query, Person.class);
		return person;
	}
	
	/**
	 * @param id
	 * @return
	 */
	public boolean deletePersonById(String id){
		Person person = findPersonById(id);
		boolean status = false; 
		try {
			mongoTemplate.remove(person, COLLECTION_NAME);
			status = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return status;
	}

	/**
	 * @param person
	 */
	public void updatePerson(Person person) {
		mongoTemplate.save(person, COLLECTION_NAME);
	}
}

Once the service class is ready in hand it’s time for us to test this class, before running the test class make sure your mongodb is up and running.
SpringMongoTest.java

/**
 * 
 */
package com.spark.spring.data.mongo.test;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import org.springframework.data.mongodb.core.MongoTemplate;

import com.spark.spring.data.document.obj.Address;
import com.spark.spring.data.document.obj.Person;
import com.spark.spring.data.service.PersonService;
import com.spark.spring.data.util.SpringDataUtil;

/**
 * @author PavanKumar Mantha
 * 
 */
public class SpringMongoTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Person person = new Person();
		
		Address residenceAddress = new Address();
		residenceAddress.setId(1);
		residenceAddress.setDoorNo("7-48/4");
		residenceAddress.setStreet("Shankar Nagar");
		residenceAddress.setCity("Hyderabad");
		residenceAddress.setCountry("India");
		residenceAddress.setZipcode("500098");
		
		Address officeAddress = new Address();
		officeAddress.setId(2);
		officeAddress.setDoorNo("Ness Technologies");
		officeAddress.setStreet("Maximus 2B, Raheja Mind Space, HitechCity");
		officeAddress.setCity("Hyderabad");
		officeAddress.setCountry("India");
		officeAddress.setZipcode("500098");
		
		List<Address> addresses = new ArrayList<>();
		addresses.add(residenceAddress);
		addresses.add(officeAddress);
		
		person.setId(1);
		person.setFirstName("Kameswara Pavan Kumar");
		person.setLastName("Mantha");
		Set<String> phoneNumbers = new HashSet<>();
		phoneNumbers.add("9949493991");
		phoneNumbers.add("9603434035");
		person.setPhoneNumbers(phoneNumbers);
		person.setAddress(addresses);
		
		PersonService personService = (PersonService) SpringDataUtil
				.getObject("personService");

		personService.deleteAll();
		
		if(personService.addPerson(person)){
			System.out.println("Person Added");
		}

	}
}

if every thing goes well and good then we should see some thing as below as output in mongo database.
mongodb-output

Happy Coding, Happy MongoDB 🙂