Spring 4 + MongoDB + Gradle Integration Annotation Example

By Arvind Rai, December 21, 2014
On this page we will learn Spring 4 and MongoDB which is a NoSQL database. MongoDB stores data in BSON format which is Binary JSON. MongoDB is easy to use and perform faster. Spring provides different classes to work with MongoDB . MongoRepository is used to define our repository class in which we define different methods to retrieve data. In configuration class, we have MongoDbFactory and MongoTemplate. MongoDbFactory provides database instance and MongoTemplate provides different methods for MongoDB database transaction. In this example, we will save some employee and apply our repository methods to retrieve data from MongoDB.

Software Required to Run Example

To run the example we need the following software.
1. JDK 6
2. Gradle
3. Eclipse
4. MongoDB

Install MongoDB Server

Find the steps to install MongoDB server.
1. To install MongoDB Server, visit the URL Install MongoDB and if looking for windows, visit the URL Install MongoDB on Windows
2. Download Binary file and install.
3. Create \data\db directory in MongoDB home.
4. To run the server, go to bin directory using command prompt and run mongod file using the command mongod.exe --dbpath C:\MongoDB-2.6\data\db

Project Structure in Eclipse

Find the project structure of or demo in eclipse.
Spring 4 + MongoDB  + Gradle  Integration Annotation Example

Gradle for Spring data and MongoDB Boot

Find the build.gradle file that will use spring-boot-starter-data-mongodb.
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'Concretepage'
version = '1.0-SNAPSHOT' 
repositories {
    maven { url "https://repo.spring.io/libs-release" }
dependencies {
 	compile 'org.springframework.boot:spring-boot-starter-data-mongodb:1.2.0.RELEASE'
 	compile 'org.springframework.boot:spring-boot-starter-security:1.2.0.RELEASE'

Create an Entity Class

Find the entity class for the demo. Using @Id annotation we create an identifier for our entity.
package com.concretepage.mongodb.entity;
import org.springframework.data.annotation.Id;
public class Employee { 
	public Integer id;
	public String name;
        public Integer age;
	public Employee(Integer id, String name, Integer age){
		this.id = id;

Create Repository Class using MongoRepository

Spring data provides MongoRepository using which we create our repository class to add required methods which retrieves data. Queries are written in BSON syntax. ?0 is used to get parameter value. If we want to filter property, we can use value and fields keys. Value is which we will pass as input and fields are those properties which will be populated.
package com.concretepage.mongodb;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Component;
import com.concretepage.mongodb.entity.Employee;
public interface EmployeeRepository extends MongoRepository<Employee, String> {
    @Query("{ 'name' : ?0 }")
    Employee getEmployeeByName(String name);
    @Query(value="{ 'age' : ?0}", fields="{ 'name' : 1, 'id' : 1}")
    List getEmployeeByAge(int age);

Configuration Class: MongoDbFactory and MongoTemplate

Create a configuration class to declare MongoDbFactory , MongoTemplate and our repository class i.e EmployeeRepository.
MongoDbFactory: Create database instances. In our example, we are creating a database with the name concretepage.
MongoClient: Using IP and port of MongoDB server, MongoClient create an instance for the client.
UserCredentials: Provides the instance to set username and password of MongoDB server. By default both are blank.
SimpleMongoDbFactory: Provides MongoDB instance using MongoClient, database name and UserCredentials.
MongoTemplate: It has basic sets of operation for MongoDB.
Find the configuration class.
package com.concretepage.mongodb.config;  
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.authentication.UserCredentials;
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 com.concretepage.mongodb.EmployeeRepository;
import com.mongodb.MongoClient;
@EnableMongoRepositories(basePackages="com.concretepage.mongodb" )
public class MongoDBConfig {
    EmployeeRepository employeeRepository;  
    public  MongoDbFactory mongoDbFactory() throws Exception {
    	MongoClient mongoClient = new MongoClient("localhost",27017);
    	UserCredentials userCredentials = new UserCredentials("","");
        return new SimpleMongoDbFactory(mongoClient, "concretepage",userCredentials);
    public MongoTemplate mongoTemplate() throws Exception {
        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
        return mongoTemplate;

Main Class: Save Data and Fetch using Repository Instance

We will save some employee in MongoDB and then retrieve data using our repository method.
 package com.concretepage.mongodb;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.concretepage.mongodb.config.MongoDBConfig;
import com.concretepage.mongodb.entity.Employee;
public class Main {
	public static void main(String[] args) {
	   AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	   EmployeeRepository employeeRepository = ctx.getBean(EmployeeRepository.class);
	   Employee ram = new Employee(1,"Ram",20);
	   Employee shyam = new Employee(2,"Shyam",19);
	   Employee mohan = new Employee(3,"Mohan",20);
	   Employee krishn = new Employee(4,"Krishn",20);
    	   //Delete if exists already
    	   //Save employee
    	   //Get employee By Name
    	   Employee emp = employeeRepository.getEmployeeByName(shyam.name);
    	   //Fetch all employee for the age
    	   List employees = employeeRepository.getEmployeeByAge(20);
    	   System.out.println("----employee for the age 20----");
    	   for (Employee employee : employees) {
Find the Output
----employee for the age 20----
To check output in MongoDB console, find the below steps.
1. To check output in MongoDB, open command prompt and go to bin directory and run
2. In our example, we have taken database name as concretepage. To go in database use the command
use concretepage
3. To check the data of employee entity, run the query as
Spring 4 + MongoDB  + Gradle  Integration Annotation Example
Enjoy Learning.

Download Source Code


©2024 concretepage.com | Privacy Policy | Contact Us