Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Spring MVC and MongoDB

    • 0
    • 1
    • 0
    • 0
    • 3
    • 0
    • 0
    • 0
    • 15.6k
    Comment on it

    Repository Class Using MongoDB :

    Spring has the capability to create loose coupling application's layers. To dealing with database we create a DAO layer. In Spring DAO layer contains the Repository class this class is responsible for all database related operations. In this example we will use the @Repository annotaion to lable the Repository class.

    MongoDB is different kind of database, it is scalable, NoSQL Document Oriented database. MongoDB holds data in the form of document and collections. If we compare the MongoDb to other Relational databases then we can say that the document in the MongoDB is like a row in Relational database and collection is like a table which holds the collection of documents.

    Document is like a key-value information. Document holds the all information of a single entity like a row in relational database. Key in the documents are called field. Collection is a group of documents. It is like a table in relational database.

    Spring provides the MongoTemplate class to handle the database related operations. This class will provides the important functions like save(), insert(), findAll(), remove () etc. which facilitate the developer to use the MongoDB without any problem. The following sample code describes some of the functions.

    Example of Spring MVC and MongoDB : Use following dependencies in pom.xml


    Create model class :

    package com.evon.model;
    public class Customer {
        private String id;
        private String name;
        public String getId() {
            return id;
        public void setId(String id) {
   = id;
        public String getName() {
            return name;
        public void setName(String name) {
   = name;

    Create DAO interface :

    package com.evon.service;
    import java.util.List;
    import com.evon.model.Customer;
    public interface CustomerDAO {
        public void addCustomer(Customer customer);
        public List<Customer> listCustomer();
        public void deleteCustomer(Customer customer);
        public void updateCustomer(Customer customer);

    Create DAO Implementation class :

    package com.evon.service;
    import java.util.List;
    import java.util.UUID;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Repository;
    import com.evon.model.Customer;
    public class CustomerDAOImpl implements CustomerDAO{
        private MongoTemplate mongoTemplate;
        public static final String COLLECTION&#95;NAME = "customer";
        public void addCustomer(Customer customer) {
            if (!mongoTemplate.collectionExists(Customer.class)) {
            mongoTemplate.insert(customer, COLLECTION&#95;NAME);
        public List<Customer> listCustomer() {
            return mongoTemplate.findAll(Customer.class, COLLECTION&#95;NAME);
        public void deleteCustomer(Customer customer) {
            mongoTemplate.remove(customer, COLLECTION&#95;NAME);
        public void updateCustomer(Customer customer) {
            mongoTemplate.insert(customer, COLLECTION&#95;NAME);        

    Create a controller class :

    package com.evon.controller;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.util.StringUtils;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.servlet.View;
    import org.springframework.web.servlet.view.RedirectView;
    import com.evon.model.Customer;
    import com.evon.service.CustomerDAO;
    public class CustomerController {  
        private CustomerDAO customerDao;
        @RequestMapping(value = "/customer", method = RequestMethod.GET)  
        public String getCustomerList(ModelMap model) {  
            model.addAttribute("customerList", customerDao.listCustomer());  
            return "output";  
        @RequestMapping(value = "/customer/save", method = RequestMethod.POST)  
        public View createCustomer(@ModelAttribute Customer customer, ModelMap model) {
            if(StringUtils.hasText(customer.getId())) {
            } else {
            return new RedirectView("/spring-mongodb/customer");  
        @RequestMapping(value = "/customer/delete", method = RequestMethod.GET)  
        public View deleteCustomer(@ModelAttribute Customer customer, ModelMap model) {  
            return new RedirectView("/spring-mongodb/customer");  


        <h2>Welcome to Home Page.</h2>
            <a href="customer">Click here</a> to Register Customer.


    <%@ taglib prefix="c" uri="" %>
        <h2>Here is a simple CRUD using Spring MVC and MongoDB.</h2>
            <form action="customer/save" method="post">
                <input type="hidden" name="id">
                <label for="name">Customer Name</label>
                <input type="text" id="name" name="name"/>
                <input type="submit" value="Submit"/>
        <table border="1">
            <c:forEach var="customer" items="${customerList}">
                    <input type="button" value="delete" onclick="window.location='customer/delete?id=${}'"/></td>


    Spring With MongoDB Web Application


    And spring configuration file : WEB-INF/dispatcher-servlet.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns=""
        <context:component-scan base-package="com.evon.service" />
        <context:component-scan base-package="com.evon.controller" />
        <!-- Factory bean that creates the Mongo instance -->
        <bean id="mongo" class="">
            <property name="host" value="localhost" />
        <!-- MongoTemplate for connecting and quering the documents in the database -->
        <bean id="mongoTemplate" class="">
            <constructor-arg name="mongo" ref="mongo" />
            <constructor-arg name="databaseName" value="test" />
        <!-- Use this post processor to translate any MongoExceptions thrown in @Repository annotated classes -->
        <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
           <bean id="jspViewResolver"
              p:suffix=".jsp" />    

    Output : Output will same for both of the applications:

    home screen



 3 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: