DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Spring Data: Easy MongoDB Migration Using Mongock
  • Advanced Search and Filtering API Using Spring Data and MongoDB
  • Manage Hierarchical Data in MongoDB With Spring
  • Spring Data: Data Auditing Using JaVers and MongoDB

Trending

  • Java Parallel GC Tuning
  • Deploy a Session Recording Solution Using Ansible and Audit Your Bastion Host
  • 5 Web3 Trends to Follow in 2023
  • API Design
  1. DZone
  2. Data Engineering
  3. Databases
  4. Spring Data MongoDB Hello World with Spring MVC: Example

Spring Data MongoDB Hello World with Spring MVC: Example

This article presents detailed steps on what is needed to get started with Spring Data MongoDB while you are working with a Spring MVC web application.

Ajitesh Kumar user avatar by
Ajitesh Kumar
·
Ajitesh Kumar user avatar by
Ajitesh Kumar
·
Aug. 18, 14 · Interview
Like (2)
Save
Tweet
Share
72.67K Views

Join the DZone community and get the full member experience.

Join For Free

This article presents detailed steps on what is needed to get started with Spring Data MongoDB while you are working with a Spring MVC web application. The article assumes that you have got the Spring MVC application setup done.

Step 1: Create Documents in MongoDB

One could download MongoDB from http://www.mongodb.org/downloads page. Once downloaded, do the following to get started.

  • Open a command prompt & goto bin folder found within MongoDB root folder.
  • Before starting MongoDB server, create the data directory within root folder.
  • Start the MongoDB server with command such as “mongod -dbpath <path-to-mongodb-root-folder>”
  • Open another command prompt and goto bin folder.
  • Execute “mongo” command and you are all set. Access various DB commands at http://docs.mongodb.org/manual/reference/command/.
  • As there is no command to create the database, give “use testdb” and testdb would be created.
  • Create a collection using following command – db.createCollection( “users” )
  • Check whether the collection is created by executing “show collections” command.
  • Insert records using command: db.runCommand( { insert: “users”, documents: [ { _id: 1, firstname: "ajitesh", lastname: "shukla" }] } )
  • Check the document using command, db.testdb.find()

Step 2: Spring Data MongoDB Libraries

Download following libraries and place them within WEB-INF/lib folder and the classpath. These are latest libraries at the time of writing the blog.

  • mongo-java-driver-2.12.1
  • spring-data-commons-1.7.2.RELEASE
  • spring-data-mongodb-1.4.2.RELEASE
  • slf4j-api-1.7.7.jar (runtime dependency)

Step 3: Create Users Class

Create User class pertaining to “users” document within MongoDB. Following is the sample code:

package com.vitalflux.hellomongo;

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

@Document(collection="users")
public class Users {

    @Id
    private String id;

    private String firstname;
    private String lastname;

    public Users() {}

    public Users(String firstName, String lastName) {
        this.firstname = firstName;
        this.lastname = lastName;
    }

 /**
 * @return the id
 */
public String getId() {
return id;
}

/**
 * @param id the id to set
 */
public void setId(String id) {
this.id = id;
}

/**
 * @return the firstName
 */
public String getFirstName() {
return firstname;
}

/**
 * @param firstName the firstName to set
 */
public void setFirstName(String firstName) {
this.firstname = firstName;
}

/**
 * @return the lastName
 */
public String getLastName() {
return lastname;
}

/**
 * @param lastName the lastName to set
 */
public void setLastName(String lastName) {
this.lastname = lastName;
}

}

Step 4: Create UsersRepository Interface

package com.vitalflux.mongo.repositories;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import com.vitalflux.hellomongo.Users;

@Repository
public interface UsersRepository extends MongoRepository<Users, String>{
}

Step 5: Create A Controller

package com.vitalflux.hellomongo;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.vitalflux.mongo.repositories.UsersRepository;

@Controller
public class HelloMongoController {

@Autowired
private UsersRepository repository;

@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView helloWorld( ModelMap model ) {
List users = repository.findAll();

ModelAndView modelAndView = new ModelAndView("index");
modelAndView.addObject("users", users );
return modelAndView;
}
}

Step 6: Configure Spring-Servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
<strong>xmlns:mongo="http://www.springframework.org/schema/data/mongo"</strong>
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
<strong>     http://www.springframework.org/schema/data/mongo
     >">

<context:component-scan base-package="com.vitalflux.hellomongo" />
<context:component-scan base-package="com.vitalflux.mongo.repositories" />

     <!-- Configuration defining views files -->

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/views/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

<strong><!-- 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>

<mongo:repositories base-package="com.vitalflux.mongo.repositories" />
</strong>
</beans>

Step 7: Create A View, index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.List"%>
<%@ page import="com.vitalflux.hellomongo.Users"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<%
List<Users> users = (List<Users>) request.getAttribute( "users" );
%>
<%
for (Users user : users) {
pageContext.setAttribute("firstname", user.getFirstName() );
%>
<div>${firstname}</div>
<%
}
%>
</body>
</html>
MongoDB Spring Data Spring Framework Data (computing) Command (computing)

Published at DZone with permission of Ajitesh Kumar. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Spring Data: Easy MongoDB Migration Using Mongock
  • Advanced Search and Filtering API Using Spring Data and MongoDB
  • Manage Hierarchical Data in MongoDB With Spring
  • Spring Data: Data Auditing Using JaVers and MongoDB

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: