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

    <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-orm</artifactId>
                <version>3.2.0.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>3.2.0.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.data</groupId>
                <artifactId>spring-data-mongodb</artifactId>
                <version>1.2.0.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
        </dependencies>
    

    Create model class : Customer.java

    package com.evon.model;
    import org.springframework.data.annotation.Id;
    import org.springframework.data.mongodb.core.mapping.Document;
    
    @Document
    public class Customer {
    
        @Id
        private String id;
        private String name;
    
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }
    

    Create DAO interface : CustomerDAO.java

    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 : CustomerDAOImpl.java

    package com.evon.service;
    import java.util.List;
    import java.util.UUID;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.mongodb.core.MongoTemplate;
    import org.springframework.stereotype.Repository;
    import com.evon.model.Customer;
    
    @Repository
    public class CustomerDAOImpl implements CustomerDAO{
    
        @Autowired
        private MongoTemplate mongoTemplate;
    
        public static final String COLLECTION&#95;NAME = "customer";
    
        public void addCustomer(Customer customer) {
            if (!mongoTemplate.collectionExists(Customer.class)) {
                mongoTemplate.createCollection(Customer.class);
            }       
            customer.setId(UUID.randomUUID().toString());
            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 : CustomerController.java

    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;
    
    @Controller    
    public class CustomerController {  
    
        @Autowired
        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())) {
                customerDao.updateCustomer(customer);
            } else {
                customerDao.addCustomer(customer);
            }
            return new RedirectView("/spring-mongodb/customer");  
        }
    
        @RequestMapping(value = "/customer/delete", method = RequestMethod.GET)  
        public View deleteCustomer(@ModelAttribute Customer customer, ModelMap model) {  
            customerDao.deleteCustomer(customer);  
            return new RedirectView("/spring-mongodb/customer");  
        }    
    }
    

    index.jsp

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

    WEB-INF/jsp/output.jsp

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
    <body>
        <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"/>
            </form>
    
        <table border="1">
            <c:forEach var="customer" items="${customerList}">
                <tr>
                    <td>${customer.name}</td><td>
                    <input type="button" value="delete" onclick="window.location='customer/delete?id=${customer.id}'"/></td>
                </tr>
            </c:forEach>
        </table>    
    </body>
    </html>
    

    WEB-INF/Web.xml

    Spring With MongoDB Web Application

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </context-param>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    

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

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:p="http://www.springframework.org/schema/p"
           xsi:schemaLocation="
           http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/context 
           http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    
        <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="org.springframework.data.mongodb.core.MongoFactoryBean">
            <property name="host" value="localhost" />
        </bean>
    
        <!-- MongoTemplate for connecting and quering the documents in the database -->
        <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
            <constructor-arg name="mongo" ref="mongo" />
            <constructor-arg name="databaseName" value="test" />
        </bean>
    
        <!-- Use this post processor to translate any MongoExceptions thrown in @Repository annotated classes -->
        <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
    
           <bean id="jspViewResolver"
              class="org.springframework.web.servlet.view.InternalResourceViewResolver"
              p:prefix="/WEB-INF/jsp/"
              p:suffix=".jsp" />    
    </beans>
    

    Output : Output will same for both of the applications:

    home screen



    screen-2



    screen-3

 3 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
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: