Friday, 11 November 2011

Spring + mongoDB


Database side -
Step 1: Download mongoDB from the following location : http://www.mongodb.org/downloads
Step 2: Create folder /data/db in your drive in which mongoDB is intalled.
Step 3: Run mongod located in bin folder. By default it will start listening on port 27017.
Application side -
Step 4: Add the following dependencies in your pom.xml.

<!-- Spring Data mongoDB Module -->
<dependency>
 <groupId>org.springframework.data</groupId>
 <artifactId>spring-data-mongodb</artifactId>
 <version>1.0.0.M2</version>
</dependency>

<!-- mongoDB Java Driver -->
<dependency>
 <groupId>org.mongodb</groupId>
 <artifactId>mongo-java-driver</artifactId>
 <version>2.5.2</version>
</dependency>
Step 5: Create a config file (e.g. spring-mongo-config.xml) in the resources folder and add the following:

<?xml version="1.0" encoding="UTF-8"?>
<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="localhost" port="27017" />
 <bean id="mongoTemplate" 
  class="org.springframework.data.document.mongodb.MongoTemplate">
  <constructor-arg ref="mongo" />
  <constructor-arg name="databaseName" value="company" />
  <constructor-arg name="defaultCollectionName" value="employees" />
 </bean>
</beans>
Step 6: Here is the SpringMongoExample class which connects to mongoDB and stores an employee object in the database:

package com.example.spring.mongo;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.data.document.mongodb.MongoOperations;
import org.springframework.data.document.mongodb.query.Criteria;
import org.springframework.data.document.mongodb.query.Query;

import com.example.spring.mongo.model.Employee;

public class SpringMongoExample {
    private MongoOperations mongoOperation;

    public SpringMongoExample() {
         ApplicationContext appContext = new GenericXmlApplicationContext("spring-mongo-config.xml");
         MongoOperations mongoOperation = (MongoOperations) appContext.getBean("mongoTemplate");
         this.mongoOperation = mongoOperation;
    }

    public static void main(String[] args) {
        SpringMongoExample springMongoExample = new SpringMongoExample();
        Employee employee = springMongoExample.createEmployeeObject();

        springMongoExample.saveEmployee(employee);

        springMongoExample.findEmployee();
    }

    /**
     * Create data model
     * 
     * @return employee
     */
    private Employee createEmployeeObject() {
       Employee employee = new Employee();
       employee.setId(543);
       employee.setName("Ranjan Kumar");
       employee.setDepartment("Lab");
       employee.setDesignation("Architect");
       return employee;
    }

    /**
     * Save new employee in the database
     */
    private void saveEmployee(Employee employee) {
        mongoOperation.save("EmployeeDetails", employee);
    }

    /**
     * Find the newly added employee from the database
     */

    private Employee findEmployee() {
        Query query = new Query(Criteria.where("designation").is("Architect"));
        Employee storedEmployee = mongoOperation.findOne("EmployeeDetails", query, Employee.class);
        System.out.println("stored employee : " + storedEmployee.toString());
        return storedEmployee;
    }
}
And here is the Employee class:
package com.example.spring.mongo.model;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Employee", propOrder = { "id", "name", "designation", "joiningDate", "department" })
public class Employee implements Serializable {

    private final static long serialVersionUID = 1L;
    @XmlElement(name = "Id")
    protected int id;
    @XmlElement(name = "Name", required = true)
    protected String name;
    @XmlElement(name = "Designation", required = true)
    protected String designation;
    @XmlElement(name = "JoiningDate", required = true)
    @XmlSchemaType(name = "date")
    protected XMLGregorianCalendar joiningDate;
    @XmlElement(name = "Department", required = true)
    protected String department;

    /**
     * Gets the value of the id property.
     * 
     */
    public int getId() {
       return id;
    }

    /**
     * Sets the value of the id property.
     * 
     */
    public void setId(int value) {
         this.id = value;
    }

    /**
     * Gets the value of the name property.
     * 
     * @return possible object is {@link String }
     * 
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the value of the name property.
     * 
     * @param value
     *            allowed object is {@link String }
     * 
     */
    public void setName(String value) {
      this.name = value;
    }

    /**
     * Gets the value of the designation property.
     * 
     * @return possible object is {@link String }
     * 
     */
    public String getDesignation() {
         return designation;
    }

    /**
     * Sets the value of the designation property.
     * 
     * @param value
     *            allowed object is {@link String }
     * 
     */
    public void setDesignation(String value) {
       this.designation = value;
    }

    /**
     * Gets the value of the joiningDate property.
     * 
     * @return possible object is {@link XMLGregorianCalendar }
     * 
     */
    public XMLGregorianCalendar getJoiningDate() {
       return joiningDate;
    }

    /**
     * Sets the value of the joiningDate property.
     * 
     * @param value
     *            allowed object is {@link XMLGregorianCalendar }
     * 
     */
    public void setJoiningDate(XMLGregorianCalendar value) {
          this.joiningDate = value;
    }

    /**
     * Gets the value of the department property.
     * 
     * @return possible object is {@link String }
     * 
     */
    public String getDepartment() {
        return department;
    }

    /**
     * Sets the value of the department property.
     * 
     * @param value
     *            allowed object is {@link String }
     * 
     */
    public void setDepartment(String value) {
         this.department = value;
    }

}