Tuesday 10 December 2013

Getting Started with a Spring MongoDB Maven Application

This blog post gives you simple steps to setup a Spring MongoDB Project. It gives you the details as to how you can perform basic CRUD operations in MongoDB using Spring. Assuming your Eclipse already has Maven Support following are the steps :

Step 1

From the New -> Project Menu select Maven Project. Click on next -


Step 2

You will be prompted to select an archetype. Find and select maven-archetype-webapp as the Artifact Id and click Next -


Step 3

Enter your Project Name in the Artifact Id field and Group Name in the Group Id field and click Finish. A project with the given name will appear in your Project Explorer


Step 4

To deploy this Web Project on Tomcat Web Server, Right Click on the Project select Properties. Under  Project Facets, change to faceted form check Dynamic Web Module and click OK.


Step 5

Also in the Properties menu, Deployment Assembly make sure you add java build path entries for Maven Dependencies -






Step 6

Delete the webapp folder in src -> main. Create a spring-servlet.xml in the WEB-INF folder. This is the spring context file which has all the context configurations. Also make sure you have web.xml (Deployment Descriptor) in your WEB-INF folder. Your final directory structure should look like this -



Step 7

To include all the required jars into your project, add the following dependencies into  your pom.xml: 





 4.0.0
 TechNirman
 SpringMongoDemo
 war
 0.0.1-SNAPSHOT
 TestProject Maven Webapp
 http://maven.apache.org
 
  
   junit
   junit
   3.8.1
   test
  
  
   org.springframework
   spring-orm
   3.2.0.RELEASE
  
  
   org.springframework
   spring-webmvc
   3.2.0.RELEASE
  
  
   org.codehaus.jackson
   jackson-mapper-asl
   1.9.12
  
  
   org.springframework.data
   spring-data-mongodb
   1.2.0.RELEASE
  
 
 
  SpringMongoDemo
 
This will make sure that you have all the required dependencies in your project


Step 8

Next are the contents of spring-servlet.xml -



 

 

 
  
 

 
  
  
 

 

 
  
   
    
   
  
 

Step 9

Contents of web.xml - 



    SpringMongoDemo
    
        spring
        
            org.springframework.web.servlet.DispatcherServlet
        
        1
    
    
        spring
        /
       

Step 10

I have a POJO class.
Student.java

package com.spring.mongo;

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

@Document
public class Student {
 @Id 
 ObjectId id;
 
 private String name;
 private String college;
 private String department;
 
 public String getDepartment() {
  return department;
 }
 public void setDepartment(String department) {
  this.department = department;
 }
 public String getCollege() {
  return college;
 }
 public void setCollege(String college) {
  this.college = college;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 
}



@Document identifies a domain object to be persisted/saved into MongoDB
@Id specifies that the variable id is to be used as the primary key


Step 11

Following is a MongoOperation class that performs the CRUD operations on Student entity 
MongoOperations.java -

package com.spring.mongo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MongoOperations {

 @Autowired
 MongoTemplate mongoTemplate;

 @RequestMapping(value = "/addStudent", method = RequestMethod.PUT)
 @ResponseBody
 String insert(@RequestBody Student student) {
  mongoTemplate.insert(student);
  return "success";
 }

 @RequestMapping(value = "/getStudent/{name}", method = RequestMethod.GET)
 @ResponseBody
 Student retrieve(@PathVariable("name") String name) {
  Query query = new Query();
  query.addCriteria(Criteria.where("name").is(name));
  Student student = mongoTemplate.findOne(query, Student.class);
  return student;
 }

 @RequestMapping(value = "/deltStudent/{name}", method = RequestMethod.DELETE)
 @ResponseBody
 String delete(@PathVariable("name") String name) {
  Query query = new Query();
  query.addCriteria(Criteria.where("name").is(name));
  mongoTemplate.remove(query, Student.class);
  return "Delete success";
 }

 @RequestMapping(value = "/updtStudent/{name}", method = RequestMethod.POST)
 @ResponseBody
 String updateDept(@PathVariable("name") String name,
   @RequestBody String newDept) {
  Query query = new Query();
  query.addCriteria(Criteria.where("name").is(name));
  Update update = new Update();
  update.set("department", newDept);
  mongoTemplate.updateFirst(query, update, Student.class);
  return "Update success";
 }
}



The MongoTemplate bean makes a connection to MongoDB and has the functions to perform most of the database related operations


Note

Run your project by right clicking on your project and selecting
Run as -> Run on server

Ensure that under Windows -> Preferences -> Java , the Installed JRE's is set to point the JDK and not the JRE. This will ensure effective development.
        
The JAVA version that is used for the current blog is Java 1.7 . Source code is available for reference/ download here under the SpringMongoDemo project


You can easily test this Project using a REST Client on any of your browsers

No comments:

Post a Comment