One could download MongoDB from http://www.mongodb.org/downloads page. Once downloaded, do the following to get started.
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.
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;
}
}
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>{
}
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;
}
}
<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"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
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
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
<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>
<!-- 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" />
</beans>
<%@ 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>
[adsenseyu1]
Artificial Intelligence (AI) agents have started becoming an integral part of our lives. Imagine asking…
In the ever-evolving landscape of agentic AI workflows and applications, understanding and leveraging design patterns…
In this blog, I aim to provide a comprehensive list of valuable resources for learning…
Have you ever wondered how systems determine whether to grant or deny access, and how…
What revolutionary technologies and industries will define the future of business in 2025? As we…
For data scientists and machine learning researchers, 2024 has been a landmark year in AI…
View Comments
Hi Ajitesh I'm glad that i found you're site randomly .You're articles on mongodb helped me a lot to learn and explore more into mongoDb using java
Thanks
Venkata Naveen Tekkem
You have not added Implementation class of this project. Look into that. As it is not useful without that.
Hi,
I am trying your example and getting below error. Could you please help
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'helloMongoController': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usersRepository': Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usersRepository': Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
Thanks,
Mahendra