a great third party support based on standard MongoDB Java Driver.
Dependencies
Following dependencies are required. Check for latest version via Nexus Central Repository:
-
spring-data-mongodb
org.springframework.data spring-data-mongodb 1.2.1.RELEASE -
mongo-java-driver
org.mongodb mongo-java-driver 2.11.1
Setup Mongo Connection, Template and Repository Scanning
This is similar idea with setting up db datasource. In this example the mongo database server is located at localhost:27017 (default). The MongoDB database name used is enrollment. The
Domain / Entity Class
Example on this post will be based on a simple Student entity class with only id and name field:
import org.springframework.data.annotation.Id; public class Student { @Id private String id; private String name; // getters & setters.. }
Without explicit configuration this entity class will be mapped into MongoDB collection name student. To override this default behavior use (collection = "...") annotation.
Repository Class
Simply add an interface extending Spring Data Repository interface. Below sample uses PagingAndSortingRepository, which extends CrudRepository which provides most basic operation. The type parameter specifies this repository operates over Student entity, with the ID type being String. Spring Data will automatically generate an implementation of this interface.
public interface StudentRepository extends PagingAndSortingRepository{ }
This repository can now be injected into controllers:
("/student") public class StudentController { private StudentRepository studentRepository; (method = GET) public String get(Model model) { Iterablestudents = studentRepository.findAll(); return "student"; } (value = "/new", method = POST) public String addNew(("student") Student student) { studentRepository.save(student); } ... }
Read More
Learn more about Spring Data and MongoDB:
- Spring Data MongoDB Reference Manual – http://static.springsource.org/spring-data/data-mongodb/docs/current/reference/html/index.html
- MongoDB Manual – http://docs.mongodb.org/manual/