Spring Core

Spring Data MongoDB Hello World Example

<p>In this tutorial&comma; we will show how to configure MongoDB using Spring Data&period; And then we will create hello world example to show how to perform CRUD operations with MongoDB and Spring Data&period;<&sol;p>&NewLine;<h2>Spring Data MongoDB Hello World Example<&sol;h2>&NewLine;<p>For this you have to do the following steps&period;<&sol;p>&NewLine;<h3><b>Step 1&colon;<&sol;b><&sol;h3>&NewLine;<p>First you have to Install <b><a href&equals;"http&colon;&sol;&sol;www&period;mongodb&period;org&sol;" target&equals;"&lowbar;blank" rel&equals;"noopener">MongoDB<&sol;a> <&sol;b>to you system&period; For windows installation <a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;2013&sol;01&sol;install-mongodb-on-windows&period;html">click here<&sol;a>&period;<&sol;p>&NewLine;<h3><b>Step 2&colon;<&sol;b><&sol;h3>&NewLine;<p>Now add the following <b>tools and libraries<&sol;b> for minimum requirement of this example&period;<&sol;p>&NewLine;<ul>&NewLine;<li><b>JDK&sol;Java 1&period;6 or later<&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"http&colon;&sol;&sol;springsource&period;com&sol;products&sol;sts" target&equals;"&lowbar;blank" rel&equals;"noopener">SpringSource Tool Suite<&sol;a> or later<&sol;b><&sol;li>&NewLine;<li><b>spring-data-mongodb-1&period;0&period;2&period;RELEASE<&sol;b> &lpar;download it from <a href&equals;"http&colon;&sol;&sol;www&period;springsource&period;org&sol;spring-data&sol;mongodb" target&equals;"&lowbar;blank" rel&equals;"noopener">here<&sol;a>&rpar;<&sol;li>&NewLine;<li><b>spring-data-commons-core-1&period;2&period;0&period;RELEASE<&sol;b> &lpar;download it from <a href&equals;"http&colon;&sol;&sol;grepcode&period;com&sol;snapshot&sol;repo1&period;maven&period;org&sol;maven2&sol;org&period;springframework&period;data&sol;spring-data-commons-core&sol;1&period;2&period;0&period;RELEASE" target&equals;"&lowbar;blank" rel&equals;"noopener">here<&sol;a>&rpar;<&sol;li>&NewLine;<li><b>java mongodb driver 2&period;10&period;1<&sol;b> &lpar;dowload it from <a href&equals;"https&colon;&sol;&sol;github&period;com&sol;mongodb&sol;mongo-java-driver&sol;downloads" target&equals;"&lowbar;blank" rel&equals;"noopener">here<&sol;a>&rpar;<&sol;li>&NewLine;<li><b>spring-core-3&period;1&period;1&period;RELEASE<&sol;b><&sol;li>&NewLine;<li><b>spring-context-3&period;1&period;1&period;RELEASE<&sol;b><&sol;li>&NewLine;<li><b>spring-asm-3&period;1&period;1&period;RELEASE<&sol;b><&sol;li>&NewLine;<li><b>spring-expression-3&period;1&period;1&period;RELEASE<&sol;b><&sol;li>&NewLine;<li><b>spring-aop-3&period;1&period;1&period;RELEASE<&sol;b><&sol;li>&NewLine;<li><b>spring-tx-3&period;1&period;1&period;RELEASE<&sol;b><&sol;li>&NewLine;<li><b>cglib-nodep-2&period;1&period;3<&sol;b><&sol;li>&NewLine;<&sol;ul>&NewLine;<div class&equals;"separator" style&equals;"clear&colon; both&semi; text-align&colon; center&semi;"><img src&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;wp-content&sol;uploads&sol;2013&sol;01&sol;springdata1&period;png" border&equals;"0" &sol;><&sol;div>&NewLine;<h3><b>Step 3&colon; <&sol;b>Spring XML configuration file<b> &lpar;mongo-config&period;xml&rpar;&colon;<&sol;b><&sol;h3>&NewLine;<p>This spring configuration file contains related bean configurations in order to run this example&period;<&sol;p>&NewLine;<pre class&equals;"highlight">&lt&semi;beans xmlns&colon;context&equals;"http&colon;&sol;&sol;www&period;springframework&period;org&sol;schema&sol;context" xmlns&colon;mongo&equals;"http&colon;&sol;&sol;www&period;springframework&period;org&sol;schema&sol;data&sol;mongo" xmlns&colon;p&equals;"http&colon;&sol;&sol;www&period;springframework&period;org&sol;schema&sol;p" xmlns&colon;xsi&equals;"http&colon;&sol;&sol;www&period;w3&period;org&sol;2001&sol;XMLSchema-instance" xmlns&equals;"http&colon;&sol;&sol;www&period;springframework&period;org&sol;schema&sol;beans" xsi&colon;schemalocation&equals;"http&colon;&sol;&sol;www&period;springframework&period;org&sol;schema&sol;beans &NewLine; http&colon;&sol;&sol;www&period;springframework&period;org&sol;schema&sol;beans&sol;spring-beans-3&period;0&period;xsd &NewLine; http&colon;&sol;&sol;www&period;springframework&period;org&sol;schema&sol;data&sol;mongo &NewLine; http&colon;&sol;&sol;www&period;springframework&period;org&sol;schema&sol;data&sol;mongo&sol;spring-mongo-1&period;0&period;xsd"&gt&semi; &NewLine; &NewLine; &lt&semi;&excl;-- Default bean name is 'mongo' --&gt&semi; &NewLine; &lt&semi;mongo&colon;mongo host&equals;"localhost" port&equals;"27017"&sol;&gt&semi; &NewLine; &lt&semi;&excl;-- Default bean name is 'mongo' --&gt&semi; &NewLine; &lt&semi;mongo&colon;mongo&gt&semi; &NewLine; &lt&semi;mongo&colon;options connections-per-host&equals;"100" &NewLine; threads-allowed-to-block-for-connection-multiplier&equals;"5" &NewLine; max-wait-time&equals;"120000000" &NewLine; connect-timeout&equals;"10000000" &NewLine; socket-keep-alive&equals;"true" &NewLine; socket-timeout&equals;"15000000" &NewLine; auto-connect-retry&equals;"true"&sol;&gt&semi; &NewLine; &lt&semi;&sol;mongo&colon;mongo&gt&semi; &NewLine; &NewLine; &lt&semi;context&colon;annotation-config&sol;&gt&semi; &NewLine; &NewLine; &lt&semi;context&colon;component-scan base-package&equals;"com&period;dineshonjava&period;mongo"&gt&semi; &NewLine; &lt&semi;context&colon;exclude-filter type&equals;"annotation" expression&equals;"org&period;springframework&period;context&period;annotation&period;Configuration"&sol;&gt&semi; &NewLine; &lt&semi;&sol;context&colon;component-scan&gt&semi; &NewLine; &NewLine; &lt&semi;&excl;-- Offers convenience methods and automatic mapping between MongoDB JSON documents and your domain classes&period; --&gt&semi; &NewLine; &lt&semi;bean class&equals;"org&period;springframework&period;data&period;mongodb&period;core&period;MongoTemplate" id&equals;"mongoTemplate"&gt&semi; &NewLine; &lt&semi;constructor-arg ref&equals;"mongo"&sol;&gt&semi; &NewLine; &lt&semi;constructor-arg name&equals;"databaseName" value&equals;"dineshonjavaDB"&sol;&gt&semi; &NewLine; &lt&semi;&sol;bean&gt&semi; &NewLine; &NewLine;&lt&semi;&sol;beans&gt&semi; &NewLine;<&sol;pre>&NewLine;<p>The MongoTemplate is configured with a reference to a MongoDBFactoryBean &lpar;which handles the actual database connectivity&rpar; and is setup with a database name used for this example&period;<&sol;p>&NewLine;<h3><b>Step 4&colon; Domain Objects or Classes-<&sol;b><&sol;h3>&NewLine;<p><b>Employee&period;java<&sol;b> represent domain classe which spring data will use to convert them from&sol;to mongodb representation&period;<&sol;p>&NewLine;<p><b>Employee&period;java<&sol;b><&sol;p>&NewLine;<pre class&equals;"highlight">package com&period;dineshonjava&period;mongo&period;dto&semi; &NewLine; &NewLine;import org&period;springframework&period;data&period;annotation&period;Id&semi; &NewLine;import org&period;springframework&period;data&period;mongodb&period;core&period;mapping&period;Document&semi; &NewLine; &NewLine;&sol;&ast;&ast; &NewLine; &ast; &commat;author Dinesh Rajput &NewLine; &ast; &NewLine; &ast;&sol; &NewLine;&commat;Document&lpar;collection &equals; "dojCollection"&rpar; &NewLine;public class Employee &lbrace; &NewLine; &commat;Id &NewLine; private int empId&semi; &NewLine; private String empName&semi; &NewLine; private long salary&semi; &NewLine; private int empAge&semi; &NewLine; public int getEmpId&lpar;&rpar; &lbrace; &NewLine; return empId&semi; &NewLine; &rcub; &NewLine; public void setEmpId&lpar;int empId&rpar; &lbrace; &NewLine; this&period;empId &equals; empId&semi; &NewLine; &rcub; &NewLine; public String getEmpName&lpar;&rpar; &lbrace; &NewLine; return empName&semi; &NewLine; &rcub; &NewLine; public void setEmpName&lpar;String empName&rpar; &lbrace; &NewLine; this&period;empName &equals; empName&semi; &NewLine; &rcub; &NewLine; public long getSalary&lpar;&rpar; &lbrace; &NewLine; return salary&semi; &NewLine; &rcub; &NewLine; public void setSalary&lpar;long salary&rpar; &lbrace; &NewLine; this&period;salary &equals; salary&semi; &NewLine; &rcub; &NewLine; public int getEmpAge&lpar;&rpar; &lbrace; &NewLine; return empAge&semi; &NewLine; &rcub; &NewLine; public void setEmpAge&lpar;int empAge&rpar; &lbrace; &NewLine; this&period;empAge &equals; empAge&semi; &NewLine; &rcub; &NewLine; &commat;Override &NewLine; public String toString&lpar;&rpar; &lbrace; &NewLine; return "Employee &lbrack;age&equals;" &plus; empAge &plus; "&comma; empName&equals;" &plus; empName &plus; "&comma; empId&equals;" &NewLine; &plus; empId &plus; "&comma; salary&equals;" &plus; salary &plus; "&rsqb;"&semi; &NewLine; &rcub; &NewLine;&rcub; &NewLine;<&sol;pre>&NewLine;<p>Now if you look at the class more closely you will see some Spring Data specific annotations like <b><i>&commat;Id<&sol;i><&sol;b> and <i><b>&commat;Document<&sol;b> <&sol;i>&period; The <i><b>&commat;Document <&sol;b><&sol;i>annotation identifies a domain object that is going to be persisted to MongoDB&period; Now that we have a persistable domain object we can move on to the real interaction&period;<&sol;p>&NewLine;<h3><b>Step 5&colon;<&sol;b><&sol;h3>&NewLine;<p>For easy connectivity with <b>MongoDB <&sol;b>we can make use of Spring Data&&num;8217&semi;s <b>MongoTemplate <&sol;b>class&period; Here is a simple <b>HelloMongoDB <&sol;b>object that handles all &&num;8216&semi;<b>Employee<&sol;b>&&num;8216&semi; related interaction with MongoDB by means of the <b>MongoTemplate<&sol;b>&period;<&sol;p>&NewLine;<p><b>HelloMongoDB&period;java<&sol;b><&sol;p>&NewLine;<pre class&equals;"highlight">package com&period;dineshonjava&period;mongo&period;main&semi; &NewLine; &NewLine;import java&period;util&period;List&semi; &NewLine; &NewLine;import org&period;springframework&period;beans&period;factory&period;annotation&period;Autowired&semi; &NewLine;import org&period;springframework&period;data&period;mongodb&period;core&period;MongoOperations&semi; &NewLine;import org&period;springframework&period;stereotype&period;Repository&semi; &NewLine; &NewLine;import com&period;dineshonjava&period;mongo&period;dto&period;Employee&semi; &NewLine; &NewLine;&sol;&ast;&ast; &NewLine; &ast; &commat;author Dinesh Rajput &NewLine; &ast; &NewLine; &ast;&sol; &NewLine;&commat;Repository &NewLine;public class HelloMongoDB &lbrace; &NewLine; &NewLine; &commat;Autowired &NewLine; MongoOperations mongoOperations&semi; &NewLine; &NewLine; public void execute&lpar;&rpar; &lbrace; &NewLine; if &lpar;mongoOperations&period;collectionExists&lpar;Employee&period;class&rpar;&rpar; &lbrace; &NewLine; mongoOperations&period;dropCollection&lpar;Employee&period;class&rpar;&semi; &NewLine; &rcub; &NewLine; &NewLine; mongoOperations&period;createCollection&lpar;Employee&period;class&rpar;&semi; &NewLine; &NewLine; Employee employee &equals; new Employee&lpar;&rpar;&semi; &NewLine; employee&period;setEmpId&lpar;1001&rpar;&semi; &NewLine; employee&period;setEmpName&lpar;"Dinesh Rajput"&rpar;&semi; &NewLine; employee&period;setSalary&lpar;70000&rpar;&semi; &NewLine; employee&period;setEmpAge&lpar;26&rpar;&semi; &NewLine; &NewLine; mongoOperations&period;insert&lpar;employee&rpar;&semi; &NewLine; &NewLine; List&lt&semi;Employee&gt&semi; results &equals; mongoOperations&period;findAll&lpar;Employee&period;class&rpar;&semi; &NewLine; System&period;out&period;println&lpar;"Results&colon; " &plus; results&rpar;&semi; &NewLine; &rcub; &NewLine;&rcub; &NewLine;<&sol;pre>&NewLine;<h3><b>Step 6&colon; Running the Example<&sol;b><&sol;h3>&NewLine;<p>Following code shows how to run this example<&sol;p>&NewLine;<p><b>HelloMongoTestApp&period;java<&sol;b><&sol;p>&NewLine;<pre class&equals;"highlight">package com&period;dineshonjava&period;mongo&period;main&semi; &NewLine; &NewLine;import org&period;springframework&period;context&period;ConfigurableApplicationContext&semi; &NewLine;import org&period;springframework&period;context&period;support&period;ClassPathXmlApplicationContext&semi; &NewLine; &NewLine;&sol;&ast;&ast; &NewLine; &ast; &commat;author Dinesh Rajput &NewLine; &ast; &NewLine; &ast;&sol; &NewLine;public class HelloMongoTestApp &lbrace; &NewLine; &NewLine; &sol;&ast;&ast; &NewLine; &ast; &commat;param args &NewLine; &ast;&sol; &NewLine; public static void main&lpar;String&lbrack;&rsqb; args&rpar; &lbrace; &NewLine; ConfigurableApplicationContext context &equals; new ClassPathXmlApplicationContext&lpar;"mongo-config&period;xml"&rpar;&semi; &NewLine; &NewLine; HelloMongoDB hello &equals; &lpar;HelloMongoDB&rpar; context&period;getBean&lpar;"helloMongoDB"&rpar;&semi; &NewLine; hello&period;execute&lpar;&rpar;&semi; &NewLine; System&period;out&period;println&lpar; "DONE&excl;" &rpar;&semi; &NewLine; &rcub; &NewLine; &NewLine;&rcub; &NewLine;<&sol;pre>&NewLine;<p>If everything is fine then run the above main application as Java Application we will get the following output&period;<&sol;p>&NewLine;<div style&equals;"background-color&colon; &num;ff99cc&semi;"><b>output&colon;<&sol;b><br &sol;>&NewLine;log4j&colon;WARN No appenders could be found for logger &lpar;org&period;springframework&period;context&period;support&period;ClassPathXmlApplicationContext&rpar;&period;<br &sol;>&NewLine;log4j&colon;WARN Please initialize the log4j system properly&period;<br &sol;>&NewLine;Results&colon; &lbrack;Employee &lbrack;age&equals;26&comma; empName&equals;Dinesh Rajput&comma; empId&equals;1001&comma; salary&equals;70000&rsqb;&rsqb;<br &sol;>&NewLine;DONE&excl;<&sol;div>&NewLine;<h3><b><br &sol;>&NewLine;<&sol;b> <b>Download SourceCode &plus; Libs<&sol;b><br &sol;>&NewLine;<a href&equals;"https&colon;&sol;&sol;sites&period;google&period;com&sol;site&sol;dinesh9582486434&sol;my-forms&sol;MongoDBSpringHelloExample&period;zip&quest;attredirects&equals;0&amp&semi;d&equals;1" target&equals;"&lowbar;blank" rel&equals;"noopener"><b>MongoDBSpringHelloExample&period;zip<&sol;b><&sol;a><&sol;h3>&NewLine;<p><b>References<&sol;b><br &sol;>&NewLine;<b><a href&equals;"http&colon;&sol;&sol;www&period;springsource&period;org&sol;spring-data&sol;mongodb" target&equals;"&lowbar;blank" rel&equals;"noopener">Spring data for MongoDB<&sol;a><&sol;b><&sol;p>&NewLine;<p>&nbsp&semi;<&sol;p>&NewLine;<div style&equals;"background-color&colon; &num;ff99cc&semi;">                        <b>     &lt&semi;&lt&semi;<a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;authentication-to-mongodb-with-java&sol;">previous<&sol;a>&lt&semi;&lt&semi;             &vert;&vert; <a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;introduction-to-mongodb&sol;">index  <&sol;a>&vert;&vert;         &gt&semi;&gt&semi;<a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;spring-data-mongodb-insert-document&sol;">next<&sol;a>&gt&semi;&gt&semi;<&sol;b><&sol;div>&NewLine;<p>&nbsp&semi;<&sol;p>&NewLine;<div class&equals;"wp-post-navigation"> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <div class&equals;"wp-post-navigation-pre"> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;authentication-to-mongodb-with-java&sol;">Previous<&sol;a> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <&sol;div> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <div class&equals;"wp-post-navigation-next"> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;spring-data-mongodb-insert-document&sol;">Next<&sol;a> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <&sol;div> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;<&sol;div>&NewLine;<script type&equals;"text&sol;javascript">&NewLine;jQuery&lpar;document&rpar;&period;ready&lpar;function&lpar;&dollar;&rpar; &lbrace;&NewLine; &dollar;&period;post&lpar;'https&colon;&sol;&sol;dineshonjava&period;com&sol;wp-admin&sol;admin-ajax&period;php'&comma; &lbrace;action&colon; 'mts&lowbar;view&lowbar;count'&comma; id&colon; '584'&rcub;&rpar;&semi;&NewLine;&rcub;&rpar;&semi;&NewLine;<&sol;script>

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…

4 years ago

Decorator Pattern using Lambda

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

4 years ago

Delegating pattern using lambda

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

4 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;…

4 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

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

4 years ago

Scheduler @Scheduled Annotation Spring Boot

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

4 years ago