<p>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.</p>
<h2>Spring Data MongoDB Hello World Example</h2>
<p>For this you have to do the following steps.</p>
<h3><b>Step 1:</b></h3>
<p>First you have to Install <b><a href="http://www.mongodb.org/" target="_blank" rel="noopener">MongoDB</a> </b>to you system. For windows installation <a href="https://dineshonjava.com/2013/01/install-mongodb-on-windows.html">click here</a>.</p>
<h3><b>Step 2:</b></h3>
<p>Now add the following <b>tools and libraries</b> for minimum requirement of this example.</p>
<ul>
<li><b>JDK/Java 1.6 or later</b></li>
<li><b><a href="http://springsource.com/products/sts" target="_blank" rel="noopener">SpringSource Tool Suite</a> or later</b></li>
<li><b>spring-data-mongodb-1.0.2.RELEASE</b> (download it from <a href="http://www.springsource.org/spring-data/mongodb" target="_blank" rel="noopener">here</a>)</li>
<li><b>spring-data-commons-core-1.2.0.RELEASE</b> (download it from <a href="http://grepcode.com/snapshot/repo1.maven.org/maven2/org.springframework.data/spring-data-commons-core/1.2.0.RELEASE" target="_blank" rel="noopener">here</a>)</li>
<li><b>java mongodb driver 2.10.1</b> (dowload it from <a href="https://github.com/mongodb/mongo-java-driver/downloads" target="_blank" rel="noopener">here</a>)</li>
<li><b>spring-core-3.1.1.RELEASE</b></li>
<li><b>spring-context-3.1.1.RELEASE</b></li>
<li><b>spring-asm-3.1.1.RELEASE</b></li>
<li><b>spring-expression-3.1.1.RELEASE</b></li>
<li><b>spring-aop-3.1.1.RELEASE</b></li>
<li><b>spring-tx-3.1.1.RELEASE</b></li>
<li><b>cglib-nodep-2.1.3</b></li>
</ul>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2013/01/springdata1.png" border="0" /></div>
<h3><b>Step 3: </b>Spring XML configuration file<b> (mongo-config.xml):</b></h3>
<p>This spring configuration file contains related bean configurations in order to run this example.</p>
<pre class="highlight"><;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>; 
</pre>
<p>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.</p>
<h3><b>Step 4: Domain Objects or Classes-</b></h3>
<p><b>Employee.java</b> represent domain classe which spring data will use to convert them from/to mongodb representation.</p>
<p><b>Employee.java</b></p>
<pre class="highlight">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 + "]"; 
 } 
} 
</pre>
<p>Now if you look at the class more closely you will see some Spring Data specific annotations like <b><i>@Id</i></b> and <i><b>@Document</b> </i>. The <i><b>@Document </b></i>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.</p>
<h3><b>Step 5:</b></h3>
<p>For easy connectivity with <b>MongoDB </b>we can make use of Spring Data&#8217;s <b>MongoTemplate </b>class. Here is a simple <b>HelloMongoDB </b>object that handles all &#8216;<b>Employee</b>&#8216; related interaction with MongoDB by means of the <b>MongoTemplate</b>.</p>
<p><b>HelloMongoDB.java</b></p>
<pre class="highlight">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); 
 } 
} 
</pre>
<h3><b>Step 6: Running the Example</b></h3>
<p>Following code shows how to run this example</p>
<p><b>HelloMongoTestApp.java</b></p>
<pre class="highlight">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!" ); 
 } 
 
} 
</pre>
<p>If everything is fine then run the above main application as Java Application we will get the following output.</p>
<div style="background-color: #ff99cc;"><b>output:</b><br />
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).<br />
log4j:WARN Please initialize the log4j system properly.<br />
Results: [Employee [age=26, empName=Dinesh Rajput, empId=1001, salary=70000]]<br />
DONE!</div>
<h3><b><br />
</b> <b>Download SourceCode + Libs</b><br />
<a href="https://sites.google.com/site/dinesh9582486434/my-forms/MongoDBSpringHelloExample.zip?attredirects=0&;d=1" target="_blank" rel="noopener"><b>MongoDBSpringHelloExample.zip</b></a></h3>
<p><b>References</b><br />
<b><a href="http://www.springsource.org/spring-data/mongodb" target="_blank" rel="noopener">Spring data for MongoDB</a></b></p>
<p> ;</p>
<div style="background-color: #ff99cc;"> <b> <;<;<a href="https://dineshonjava.com/authentication-to-mongodb-with-java/">previous</a><;<; || <a href="https://dineshonjava.com/introduction-to-mongodb/">index </a>|| >;>;<a href="https://dineshonjava.com/spring-data-mongodb-insert-document/">next</a>>;>;</b></div>
<p> ;</p>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/authentication-to-mongodb-with-java/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/spring-data-mongodb-insert-document/">Next</a> 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '584'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…