Spring Data MongoDB Tutorial

Spring Data for MongoDB is part of the umbrella Spring Data project which aims to provide a familiar and consistent Spring-based programming model for new data stores while retaining store-specific features and capabilities.

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.

Spring Data provides a various methodologies when it comes integrating with the MongoDB, beyond using the MongoDB Template that’s supported by Spring, a Spring-Based repository concept is also used.

Regardless of the methodology that’s being used for integrating with the MongoDB, all of those aspects that you may looking for starting from easy configurable framework reaching into an efficient and productive using of those provided libraries are exist.

Here, you will find a proper explanation of integrating Spring Data with MongoDB by using Mongo Template or by using Spring Data repositories.

Business Domain & Mapping Annotations

Spring Data provides the developer a set of annotations that could be used for mapping the Business Domain classes into MongoDB collections. MongoDB organized its data through documents; those documents are organized in collections, which are arbitrary containers for a set of documents.  Usually, you will keep documents of the same type inside a single collection, where type essentially means “similarly structured”.

For setting up MongoDB follow this link, whereas the below bullet points shows you the annotations that might be used for mapping the business domain into MongoDB collections.

  • @Id – applied at the field level to mark the field used for identiy purpose.
  • @Document – applied at the class level to indicate this class is a candidate for mapping to the database. You can specify the name of the collection where the database will be stored.
  • @DBRef – applied at the field to indicate it is to be stored using a com.mongodb.DBRef.
  • @Indexed – applied at the field level to describe how to index the field.
  • @CompoundIndex – applied at the type level to declare Compound Indexes
  • @GeoSpatialIndexed – applied at the field level to describe how to geoindex the field.
  • @Transient – by default all private fields are mapped to the document, this annotation excludes the field where it is applied from being stored in the database
  • @PersistenceConstructor – marks a given constructor – even a package protected one – to use when instantiating the object from the database. Constructor arguments are mapped by name to the key values in the retrieved DBObject.
  • @Value – this annotation is part of the Spring Framework. Within the mapping framework it can be applied to constructor arguments. This lets you use a Spring Expression Language statement to transform a key’s value retrieved in the database before it is used to construct a domain object. In order to reference a property of a given document one has to use expressions like: @Value(“#root.myProperty”) where root refers to the root of the given document.
  • @Field – applied at the field level and described the name of the field as it will be represented in the MongoDB BSON document thus allowing the name to be different than the fieldname of the class.

This isn’t a proper location for discussing the all annotations provided for achieving the mapping operation, so that not all of those mentioned annotations are being used, moreover, even some annotations that considered mandatory such as @Id when EclipseLink – JPA/NoSQL is used, when it comes to use Spring Data they are not. So let’s focus on the business domain rather annotations used for one reason and it’s being the Spring Data have been doing internal mapping without any developer involvement.

User.java

package net.javabeat.springdata.jpa.data;

import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

@Document(collection="USER")
public class User {
	@Field
	private String id;
	@Field
	private String userId;
	@Field
	private String fullName;
	@Field
	private String age;
	@Field
	private String status;
	@Field
	private Address address;

	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getFullName() {
		return fullName;
	}
	public void setFullName(String fullName) {
		this.fullName = fullName;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public String getStatus() {
		return status;
	}
	public void setStatus(String status) {
		this.status = status;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
}

Address.java

package net.javabeat.springdata.jpa.data;

import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

@Document
public class Address {
	@Field
	private String addressId = "";
	@Field
	private String addressValue = "";

	public String getAddressId() {
		return addressId;
	}
	public void setAddressId(String addressId) {
		this.addressId = addressId;
	}
	public String getAddressValue() {
		return addressValue;
	}
	public void setAddressValue(String addressValue) {
		this.addressValue = addressValue;
	}
}

Setting Up Spring Data Configuration

Either you are using Spring Data for connecting your MongoDB or MongoTemplate for doing that, you have to provide your Spring Context with the required Objects.

MongoTemplate is the central class of the Spring’s MongoDB support providing a rich feature set to interact with the database. The template offers a convenience operations to create, update, delete and query for MongoDB documents and provides a mapping between your domain objects and MongoDB documents.

The mapping between Mongo documents and domain classes is done by delegating to an implementation of the interface MongoConverter that can be customized slightly. Spring provides two implementations, SimpleMappingConverter and MongoMappingConverter, but you can also create your own converter.

For instantiating a mongoTemplate you can use either JavaConfig or XML based configuration.

	<!-- Register Mongo Instance -->
	<mongo:mongo id="mongo" host="10.10.90.3" port="27017" />
	<!--  for defining mongo template -->
	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
		<constructor-arg ref="mongo" />
		<constructor-arg name="databaseName" value="JavaBeat" />
	</bean>

By providing these mentioned lines, you have the ability to locate mongoTemplate bean from the Spring Context that already initialized.

Once, you’ve acquired mongoTemplate, you have the ability of doing all operations that you want and as you would be seeing later.

At the other side, Spring Data points out the specialties of repository support for MongoDB. This builds on the core repository support that you’ve used before at the Spring Data – JPA. To use the repository concept you have to define your repository and attach the required XML element inside Spring Context XML file. Mongo namespace provides you an XML element for defining the proper repository for being used later on.

	<!-- For defining mongo repository -->
	<mongo:repositories base-package="net.javabeat.springdata.repo" />

And use @Autowired for injecting allowing Spring Data injecting the created proxy into your Bean service. Look below at the Repository and Spring Bean Injecting.

UserRepository.java

package net.javabeat.springdata.repo;

import net.javabeat.springdata.jpa.data.User;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends CrudRepository<User, String>{}

RegistrationBean.java

package net.javabeat.springdata.beans;

import net.javabeat.springdata.repo.UserRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RegistrationBean {
	@Autowired
	private UserRepository repository;

	public RegistrationBean(){

	}

	public UserRepository getRepository() {
		return repository;
	}

	public void setRepository(UserRepository repository) {
		this.repository = repository;
	}
}

And use the element component-scan for determining the required bean. By using Spring Data repository you have the same ability that Mongo Template offers.

Maven Configuration

To configure using of MongoTemplate or Spring Data repository, you have to add the below dependencies in your maven configurations.

pom.xml

		<!-- Dependency for MongoDB Java connector -->
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>2.11.4</version>
		</dependency>
		<!-- Spring Data Mongo Support -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-mongodb</artifactId>
			<version>1.4.1.RELEASE</version>
		</dependency>
		<!--  Spring Data commons -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-commons</artifactId>
			<version>1.5.0.RELEASE</version>
		</dependency>

Spring Data MongoDB Example Application

Find below the Spring Data MongoDB application that should persist two documents of type User into MongoDB.

Executable.java

package net.javabeat.springdata.executable;

import net.javabeat.springdata.beans.RegistrationBean;
import net.javabeat.springdata.jpa.data.Address;
import net.javabeat.springdata.jpa.data.User;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;

public class Executable {
	public static RegistrationBean registrationBean;
	public static ClassPathXmlApplicationContext context;

	static {
		// Acquire Context
		context = new ClassPathXmlApplicationContext("SpringContext.xml");
	}

	public static void main(String [] args) throws Exception{
		// Create by MongoTemplate
		createUserThroughMonogoTamplate();
		// Create By Spring Data
		CreateUserThoughMongoRepository();
	}

	public static void createUserThroughMonogoTamplate(){
		MongoTemplate mongoOps = (MongoTemplate)context.getBean("mongoTemplate");
		User user = new User();
		user.setId("200");
		user.setFullName("Mongo Template");
		user.setStatus("A");
		user.setAge("29");
		Address address = new Address();
		address.setAddressId("200");
		address.setAddressValue("UK/London");
		user.setAddress(address);
		mongoOps.insert(user);
	}

	public static void CreateUserThoughMongoRepository(){
		User user = new User();
		user.setId("201");
		user.setFullName("Spring Data");
		user.setStatus("B");
		user.setAge("25");
		Address address = new Address();
		address.setAddressId("201");
		address.setAddressValue("UK/Manchester");
		user.setAddress(address);
		RegistrationBean bean = (RegistrationBean)context.getBean("registrationBean");
		bean.getRepository().save(user);
	}
}

Saved Documents

The below snapshot shows you the documents that are saved into MongoDB.
Spring Data MongoDB

Summary

Spring Data provides you an awesome ways for integrating the MongoDB. Regardless of using MongoTemplate that already provided by Spring iteself, Spring Data provides a special repository for being used with the MongoDB. Those repositories provides you a full access of inserting, deleting, updating and reading the documents from MongoDB’s collections without any need for care about the implementation.

Reference

Comments

comments

About Amr Mohammed

Speak Your Mind

*