Spring MVC CRUD using MongoDB Tutorial

Tech Lead & Architect | 13+ Years in Cloud, Backend, and AI - Experienced software engineer with expertise in Java, Spring Boot, Microservices, Angular, React, Kafka, DevOps, Python, PySpark, Databricks, and Generative AI. Certified in TOGAF, AWS, and Google Cloud. Passionate about building scalable, secure, and high-performance systems. Enthusiast in Data Engineering & Agentic AI. Author of 1,200+ technical articles sharing insights across diverse tech stacks.
Date: 2018-04-19
Building a Spring MVC Application with MongoDB: A Comprehensive Guide
This article details the process of creating a simple Spring MVC application that interacts with a MongoDB database. We'll cover the fundamental concepts of Spring MVC, MongoDB, and how to integrate them to perform basic Create, Read, Update, and Delete (CRUD) operations on a user database. This guide assumes a basic understanding of Java and web application development principles.
Understanding the Architecture: Model-View-Controller (MVC)
Before diving into the specifics, let's review the Model-View-Controller (MVC) design pattern. MVC is a widely used architectural pattern for building user interfaces. It separates an application into three interconnected parts:
The Model: This component represents the data of the application. In our case, the model would be the User data stored in the MongoDB database. It handles data storage, retrieval, and manipulation. Think of it as the "brains" of the application, containing the core business logic and data.
The View: The view is responsible for presenting the data to the user. This is typically the user interface (UI), which could be a web page, a desktop application, or any other means of displaying information. It's essentially what the user sees and interacts with. It receives data from the model and displays it in a user-friendly format.
The Controller: The controller acts as an intermediary between the model and the view. It receives user input from the view, processes it using the model's logic, and then updates the view accordingly. It manages the flow of data and user interactions. It's the "traffic cop," directing the communication between the other two components.
Setting up the Development Environment
To build this application, you will need several tools:
- An Integrated Development Environment (IDE) like Eclipse.
- The Java Development Kit (JDK), version 8 or higher is recommended, although the original tutorial indicated compatibility with JDK 1.7.
- Maven, a build automation tool for Java projects.
- MongoDB, a NoSQL database, version 3.6.X or higher. You'll need to have this installed and running before proceeding.
Project Setup and Structure
We'll start by creating a new Maven web application project within your IDE. Maven handles dependency management, simplifying the inclusion of necessary libraries. The project structure will follow a standard layout, typically including source code directories for Java files, resources like configuration files, and a web application directory for JSP pages and other web assets. The structure includes folders to organize the code: Java classes for the model, service, and controller, JSP files for the user interface, and configuration files to set up the Spring framework.
Dependencies and Configurations
The project’s pom.xml file (the Maven project object model) lists the necessary dependencies, including Spring MVC for the web framework, MongoDB Java driver for database interaction, and logging libraries like Log4j. These dependencies are automatically downloaded and managed by Maven.
Key Components of the Application
The application consists of several crucial Java classes:
MongoFactory: This class establishes the connection to the MongoDB database. It provides methods to access the database and specific collections (akin to tables in relational databases). It handles the connection details, like hostname and port number.
User Model: This class defines the structure of the data representing a user. It typically includes fields like user ID, name, and other relevant attributes. It maps directly to the way the user data will be stored in the MongoDB documents.
UserService: This class contains the core business logic for interacting with the user data. It implements the CRUD operations (Create, Read, Update, Delete) using methods to add new users, retrieve user lists, update existing user information, and delete users from the database. These operations translate user requests into interactions with the MongoDB database.
UserController: This is a Spring MVC controller that handles HTTP requests. It receives requests (e.g., to add a new user or view the user list), interacts with the UserService to perform the necessary operations, and then returns an appropriate response (usually a web page). It acts as the intermediary between the user's actions and the application's data layer.
Configuration Files
Several XML configuration files are essential:
spring-servlet.xml: This Spring configuration file defines the beans, sets up the Spring MVC components (like view resolvers), and connects the application to the database. It's the heart of the Spring framework configuration for the web application.web.xml: This file is a standard deployment descriptor for web applications, defining the dispatcher servlet (the core component of Spring MVC that handles incoming requests). It configures the web application's deployment within a servlet container like Tomcat.
User Interface (JSP Pages)
The application includes JSP (JavaServer Pages) files for the user interface:
welcome.jsp: This page displays a list of users retrieved from the database.form.jsp: This page provides a form for adding or updating user data. Users interact with these pages through a web browser.
Deployment and Testing
Once all the components are created and configured, the application can be deployed to a servlet container like Tomcat. This involves packaging the application and deploying it into the Tomcat webapps directory. After deployment, the application can be accessed via a web browser to test the CRUD functionality. You should be able to add, view, update, and delete user records within the MongoDB database through the web interface.
Conclusion
This comprehensive guide outlines the development of a Spring MVC application leveraging MongoDB as its database. By separating concerns with the MVC pattern and utilizing Maven for dependency management, this process provides a structured approach to building robust and maintainable web applications. Remember that proper database connection settings and correct deployment within a servlet container are crucial for successful execution.