MongoDB with Spring Data


The Spring Data MongoDB project provides integration with the MongoDB document database. Key functional areas of Spring Data MongoDB are a POJO centric model for interacting with a MongoDB DBCollection and easily writing a Repository style data access layer.

Features

  • Spring configuration support using Java based @Configuration classes or an XML namespace for a Mongo driver instance and replica sets.
  • MongoTemplate helper class that increases productivity performing common Mongo operations. Includes integrated object mapping between documents and POJOs.
  • Exception translation into Spring's portable Data Access Exception hierarchy
  • Feature Rich Object Mapping integrated with Spring's Conversion Service
  • Annotation based mapping metadata but extensible to support other metadata formats
  • Persistence and mapping lifecycle events
  • Low-level mapping using MongoReader/MongoWriter abstractions
  • Java based Query, Criteria, and Update DSLs
  • Automatic implementation of Repository interfaces including support for custom finder methods.
  • QueryDSL integration to support type-safe queries.
  • Cross-store persistance - support for JPA Entities with fields transparently persisted/retrieved using MongoDB
  • Log4j log appender
  • GeoSpatial integration
  • Map-Reduce integration
  • JMX administration and monitoring
  • CDI support for repositories
  • GridFS support

The recommended way to get started using spring-data-mongodb in your project is with a dependency management system - the snippet below can be copied and pasted into your build.

<dependencies>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>
        <version>1.9.1.RELEASE</version>
    </dependency>
</dependencies>

In this tutorial, we show you how to use "SpringData for MongoDB" framework, to perform CRUD operations in MongoDB, via Spring's annotation and XML schema.

Spring Configuration, Annotation and XML


Here, we show you two ways to configure Spring data and connect to MongoDB, via annotation and XML schema.

MongoDB via annotation

Extends the AbstractMongoConfiguration is the fastest way, it helps to configure everything you need to start, like mongoTemplate object.

package com.javavillage.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import com.mongodb.MongoClient;

@Configuration
public class SpringMongoConfig1 {

	public @Bean
	MongoDbFactory mongoDbFactory() throws Exception {
		return new SimpleMongoDbFactory(new MongoClient(), "yourdb");
	}

	public @Bean
	MongoTemplate mongoTemplate() throws Exception {		
		MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());				
		return mongoTemplate;		
	}
}

And load it with AnnotationConfigApplicationContext :

    ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
    MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");

MongoDB via XML schema

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mongo="http://www.springframework.org/schema/data/mongo"
	xsi:schemaLocation="http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/data/mongo
          http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<mongo:mongo host="127.0.0.1" port="27017" />
	<mongo:db-factory dbname="yourdb" />

	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
		<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
	</bean>

</beans>

And include it with Spring's GenericXmlApplicationContext :

   ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml");
   MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");