Spring MVC and MongoDB tutorial

This tutorial has the goal to show how can be easy to create a new Web application based on Spring and MongoDB.
You can find the code of this small application here:
https://github.com/marco76/mvcMongoExample
The prerequisite is to have MongoDB installed and started.
Spring has a module to import all the necessary for MongoDB:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.1.1.RELEASE</version>
</dependency>
In the servlet-context we configure the connection to the database and we create the template that we will use to interact with it:
<mongo:mongo id="mongo" host="localhost" port="27017"/>
<beans:bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<beans:constructor-arg ref="mongo"/>
<beans:constructor-arg name="databaseName" value="jobfinder"/>
</beans:bean>
<mongo:repositories base-package="ch.genidea.mvcMongoExample.repository"/>
Here you can see how simple his our class structure:

We use a Person class to store the data in the database:
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class Person {
@Id
private ObjectId id;
private String username;
private String password;
public Person() {
}
For MongoDB we use the annotation @Document in place of the more traditional @Entity used for traditional databases.
In MainMongo.java you can find an example about how to use the Person class.
public class MainMongo {
private static final Logger log = LoggerFactory.getLogger(MainMongo.class);
public static void main(String[] args) throws Exception {
MongoOperations mongoOperations = new MongoTemplate(new Mongo(), "database");
mongoOperations.insert(new Person("marco", "marco"));
Person person = mongoOperations.findOne(new Query(Criteria.where("username").is("marco")), Person.class);
log.debug("Person found :" + person.getUsername());
mongoOperations.dropCollection("person");
}
}
To update the database we can leverage the power of spring data. It’s enough to create an interface that extends CrudRepository to have basic db features magically available:
import ch.genidea.mvcMongoExample.model.Person;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface PersonRepository extends CrudRepository<Person, Long> {
List<Person> findByUsername(String username);
}
The interface is used in our HomeController to retrieve the list of people records in the database:
@Autowired
private PersonRepository personRepository;
/**
* Home page renderer
*/
@RequestMapping(value ="/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Home page");
Iterable<Person> personList = personRepository.findAll();
model.addAttribute("personList", personList);
return"home";
}
Here the result:

Alternatively we can use MongoTemplate as in the MainMongo class or in the PersonController where we mix MongoTemplate and CrudRepository just to show the possibilities that Spring give to the developer:
We have a very poor page that allows to add a new Person:

when the user click on Save the method addPerson is called:
@Autowired
MongoTemplate mongoTemplate;
@Autowired
PersonRepository personRepository;
@RequestMapping(value ="/savePerson", method = RequestMethod.POST)
public String addPerson(@ModelAttribute("person") Person person, BindingResult result) {
List personList = personRepository.findByUsername(person.getUsername());
if (personList.size() > 0) {
System.out.println("Error username already exists");
} else {
System.out.println("Ok: new username");
mongoTemplate.save(person);
}
return "redirect:/";
}