Sunday, April 19, 2015

Connecting to MongoDB using Spring Data

In this blog I will show how easy you can connect to a MongoDB using Spring Data. For installation of MongoDB, go to http://docs.mongodb.org/manual/installation/

The dependencies needed besides standard Spring dependencies are spring-data-mongo and mongo-java-driver.
 <dependency>  
     <groupId>org.mongodb</groupId>  
     <artifactId>mongo-java-driver</artifactId>  
     <version>2.12.4</version>  
 </dependency>  
 <dependency>  
     <groupId>org.springframework.data</groupId>  
     <artifactId>spring-data-mongodb</artifactId>  
     <version>1.6.0.RELEASE</version>  
 </dependency>  

First lets create some domain objects. Department is a simple object with only only one attribute representing a department.

 public class Department {  
   
     private final String name;  
   
     public Department(String name) {  
         this.name = name;  
     }  
   
     @Override  
     public String toString() {  
         return "Department [name=" + this.name + "]";  
     }  
 }  
Second domain object is Person, which holds a reference to Department. Is also has an @Id which can be used for retrieval.
 import org.springframework.data.annotation.Id;  
 import java.util.UUID;  
   
 public class Person {  
   
   @Id  
   private final UUID id;  
   private final String name;  
   private final String title;  
   private final Department department;  
   
   public Person(String name, String title, Department department) {  
     this.id = UUID.randomUUID();  
     this.name = name;  
     this.title = title;  
     this.department = department;  
   }  
   
   public UUID getId() {  
     return this.id;  
   }  
   
   @Override  
   public String toString() {  
     return "Person{" +  
         "department=" + department +  
         ", id=" + id +  
         ", name='" + name + '\'' +  
         ", title='" + title + '\'' +  
         '}';  
   }  
 }  

Next we need a configuration that connects to the MongoDB and exposes a MongoTemplate that can be injected into repository beans.
 import org.springframework.data.mongodb.MongoDbFactory;  
 import org.springframework.data.mongodb.core.MongoTemplate;  
 import org.springframework.data.mongodb.core.SimpleMongoDbFactory;    
 import com.mongodb.DB;  
 import com.mongodb.MongoClient;  
   
 @Configuration  
 @ComponentScan("com.blogspot.jpdevelopment.mongodb")  
 public class MongoDbConfig {  
   
     @Bean  
     public MongoClient mongoClient() throws UnknownHostException {  
         return new MongoClient("localhost");  
     }  
   
     @Bean  
     public DB db() throws UnknownHostException {  
         return mongoClient().getDB("test");  
     }  
   
     @Bean  
     public MongoDbFactory mongoDbFactory() throws UnknownHostException {  
         return new SimpleMongoDbFactory(mongoClient(), "test");  
     }  
   
     @Bean  
     public MongoTemplate mongoTemplate() throws UnknownHostException {  
         return new MongoTemplate(mongoDbFactory());  
     }  
 }  
After setting up the configuration, we can create a Repository.The MongoTemplate is injected and opens up to all CRUD actions.
 import org.springframework.data.mongodb.core.MongoTemplate;  
 import org.springframework.data.mongodb.core.query.Criteria;  
 import org.springframework.data.mongodb.core.query.CriteriaDefinition;  
 import org.springframework.data.mongodb.core.query.Query;  
 import org.springframework.stereotype.Repository;  
 import java.util.UUID;  
   
 @Repository  
 public class PersonRepository {  
   
     private static final String PERSON_COLLENCTION = "person";  
   
     @Autowired  
     private MongoTemplate template;  
   
     public Person findOne(UUID id) {  
         CriteriaDefinition criteriaDefinition = Criteria.where("id").is(id);  
         Query query = new Query();  
         query.addCriteria(criteriaDefinition);  
         return this.template.findOne(query, Person.class, PERSON_COLLENCTION);  
     }  
   
     public Person save(Person person) {  
         template.save(person);  
         return person;  
     }  
 }  
Finally lets take it for a spin. Spring is started and the Repository bean is fetched from the ApplicationContext. 
First a new Person is stored and then again fetched as a new object and printed.
 public class Main {  
   
     public static void main(String[] args) {  
         AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MongoDbConfig.class);  
   
         PersonRepository personRepository = ctx.getBean(PersonRepository.class);  
         Person newPerson = new Person("Jonas", "Developer", new Department("Dev"));  
         personRepository.save(newPerson);  
   
         Person storedPerson = personRepository.findOne(newPerson.getId());  
         System.out.println(storedPerson);  
   
     }  
 }  
The output will look like this:
 Person{department=Department [name=Dev], id=9ae44c1d-a38e-4364-9848-2d7dd6538444, name='Jonas', title='Developer'}  
That was the very basic of connection to MongoDB from Java using Spring Data.