Spring Core

Spring Data MongoDB Hello World Example

In this tutorial, we will show how to configure MongoDB using Spring Data. And then we will create hello world example to show how to perform CRUD operations with MongoDB and Spring Data.

Spring Data MongoDB Hello World Example

For this you have to do the following steps.

Step 1:

First you have to Install MongoDB to you system. For windows installation click here.

Step 2:

Now add the following tools and libraries for minimum requirement of this example.

  • JDK/Java 1.6 or later
  • SpringSource Tool Suite or later
  • spring-data-mongodb-1.0.2.RELEASE (download it from here)
  • spring-data-commons-core-1.2.0.RELEASE (download it from here)
  • java mongodb driver 2.10.1 (dowload it from here)
  • spring-core-3.1.1.RELEASE
  • spring-context-3.1.1.RELEASE
  • spring-asm-3.1.1.RELEASE
  • spring-expression-3.1.1.RELEASE
  • spring-aop-3.1.1.RELEASE
  • spring-tx-3.1.1.RELEASE
  • cglib-nodep-2.1.3

Step 3: Spring XML configuration file (mongo-config.xml):

This spring configuration file contains related bean configurations in order to run this example.

<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/data/mongo
      http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
  
 <!-- Default bean name is 'mongo' -->
 <mongo:mongo host="localhost" port="27017"/>
  <!-- Default bean name is 'mongo' -->
 <mongo:mongo>
   <mongo:options connections-per-host="100"
  threads-allowed-to-block-for-connection-multiplier="5"
            max-wait-time="120000000"
            connect-timeout="10000000"
            socket-keep-alive="true"
            socket-timeout="15000000"
            auto-connect-retry="true"/>
 </mongo:mongo>
 
 <context:annotation-config/>
     
    <context:component-scan base-package="com.dineshonjava.mongo">
      <context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/>
    </context:component-scan>
    
 <!-- Offers convenience methods and automatic mapping between MongoDB JSON documents and your domain classes. -->
  <bean class="org.springframework.data.mongodb.core.MongoTemplate" id="mongoTemplate">
       <constructor-arg ref="mongo"/>
         <constructor-arg name="databaseName" value="dineshonjavaDB"/>
   </bean>
    
</beans>

The MongoTemplate is configured with a reference to a MongoDBFactoryBean (which handles the actual database connectivity) and is setup with a database name used for this example.

Step 4: Domain Objects or Classes-

Employee.java represent domain classe which spring data will use to convert them from/to mongodb representation.

Employee.java

package com.dineshonjava.mongo.dto;

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

/**
 * @author Dinesh Rajput
 *
 */
@Document(collection = "dojCollection")
public class Employee {
 @Id
 private int empId;
 private String empName;
 private long salary;
 private int empAge;
 public int getEmpId() {
  return empId;
 }
 public void setEmpId(int empId) {
  this.empId = empId;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 public long getSalary() {
  return salary;
 }
 public void setSalary(long salary) {
  this.salary = salary;
 }
 public int getEmpAge() {
  return empAge;
 }
 public void setEmpAge(int empAge) {
  this.empAge = empAge;
 }
 @Override
 public String toString() {
  return "Employee [age=" + empAge + ", empName=" + empName + ", empId="
    + empId + ", salary=" + salary + "]";
 }
}

Now if you look at the class more closely you will see some Spring Data specific annotations like @Id and @Document . The @Document annotation identifies a domain object that is going to be persisted to MongoDB. Now that we have a persistable domain object we can move on to the real interaction.

Step 5:

For easy connectivity with MongoDB we can make use of Spring Data’s MongoTemplate class. Here is a simple HelloMongoDB object that handles all ‘Employee‘ related interaction with MongoDB by means of the MongoTemplate.

HelloMongoDB.java

package com.dineshonjava.mongo.main;

import java.util.List;

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

import com.dineshonjava.mongo.dto.Employee;

/**
 * @author Dinesh Rajput
 *
 */
@Repository
public class HelloMongoDB {
 
 @Autowired
 MongoOperations mongoOperations;
 
 public void execute() {
  if (mongoOperations.collectionExists(Employee.class)) {
   mongoOperations.dropCollection(Employee.class);
   }
   
  mongoOperations.createCollection(Employee.class);
   
  Employee employee = new Employee();
  employee.setEmpId(1001);
  employee.setEmpName("Dinesh Rajput");
  employee.setSalary(70000);
  employee.setEmpAge(26);
  
  mongoOperations.insert(employee);
   
  List<Employee> results = mongoOperations.findAll(Employee.class);
  System.out.println("Results: " + results);
 }
}

Step 6: Running the Example

Following code shows how to run this example

HelloMongoTestApp.java

package com.dineshonjava.mongo.main;

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

/**
 * @author Dinesh Rajput
 *
 */
public class HelloMongoTestApp {

 /**
  * @param args
  */
 public static void main(String[] args) {
   ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("mongo-config.xml");
   
   HelloMongoDB hello = (HelloMongoDB) context.getBean("helloMongoDB");
   hello.execute();
   System.out.println( "DONE!" );
 }

}

If everything is fine then run the above main application as Java Application we will get the following output.

output:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Results: [Employee [age=26, empName=Dinesh Rajput, empId=1001, salary=70000]]
DONE!


Download SourceCode + Libs
MongoDBSpringHelloExample.zip

References
Spring data for MongoDB

 

                             <<previous<<             || index  ||         >>next>>

 

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago