Jerry Jacob's Blog

MongoDB with SpringData

Posted in Java/ J2EE by jerlinworld on August 23, 2012

Here is a simple example to show how easy to write a CRUD Java application using SpringData for MongoDB

First of all install and start MongoDB. You need only 3 files to get things going; The domain object, CRUDInterface and CRUDImplementation
Make sure you have the required mongo and spring-data-mongodb jar files in the classpath.

The domain object

package jerry.jacob.mongo.test;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document
public class Employee {
	@Id
	private String id;
	private String firstName;
	private String lastName;
	private int age;

	public Employee(String id, String firstName, String lastName,int age) {
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
                this.age = age;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", first name=" + firstName + ", last name=" + lastName + ", age=" + age + "]";
	}
}

CRUDInterface

package jerry.jacob.mongo.test;

import java.util.List;
import com.mongodb.WriteResult;

public interface CRUDInterface {
	public List getAllObjects();

	public void saveObject(O object);

	public O getObject(String id);

	public WriteResult updateObject(String id, String name);

	public void deleteObject(String id);

	public void createCollection();

	public void dropCollection();
}

CRUDImplementation

package jerry.jacob.mongo.test;

import java.util.List;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import com.mongodb.WriteResult;

public class CRUDImplementation implements CRUDInterface {
	MongoTemplate mongoTemplate;

	public void setMongoTemplate(MongoTemplate mongoTemplate) {
		this.mongoTemplate = mongoTemplate;
	}

	/**
	 * Get all Employees.
	 */
	public List getAllObjects() {
		return mongoTemplate.findAll(Employee.class);
	}

	/**
	 * Saves an Employee.
	 */
	public void saveObject(Employee employee) {
		mongoTemplate.insert(employee);
	}

	/**
	 * Gets an Employee for a particular id.
	 */
	public Employee getObject(String id) {
		return mongoTemplate.findOne(new Query(Criteria.where("id").is(id)),
				Employee.class);
	}

	/**
	 * Updates an Employee name for a particular id.
	 */
	public WriteResult updateObject(String id, String lastName) {
		return mongoTemplate.updateFirst(
				new Query(Criteria.where("id").is(id)),
				Update.update("lastName", lastName), Employee.class);
	}

	/**
	 * Delete an Employee for a particular id.
	 */
	public void deleteObject(String id) {
		mongoTemplate
				.remove(new Query(Criteria.where("id").is(id)), Employee.class);
	}

	/**
	 * Create a Employee collection if the collection does not already exists
	 */
	public void createCollection() {
		if (!mongoTemplate.collectionExists(Employee.class)) {
			mongoTemplate.createCollection(Employee.class);
		}
	}

	/**
	 * Drops the Employee collection if the collection does already exists
	 */
	public void dropCollection() {
		if (mongoTemplate.collectionExists(Employee.class)) {
			mongoTemplate.dropCollection(Employee.class);
		}
	}
}

Spring applicationContext.xml

<?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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<bean id="employeeRepository"
		class="jerry.jacob.mongo.test.CRUDImplementation">
		<property name="mongoTemplate" ref="mongoTemplate" />
	</bean>

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

	<!-- Factory bean that creates the Mongo instance -->
	<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
		<property name="host" value="localhost" />
		<property name="port" value="27017" />
	</bean>

	<!-- Activate annotation configured components -->
	<context:annotation-config />

	<!-- Scan components for annotations within the configured package -->
	<context:component-scan base-package="jerry.jacob.mongo.test">
		<context:exclude-filter type="annotation"
			expression="org.springframework.context.annotation.Configuration" />
	</context:component-scan>
</beans>

Finally Test it

      public static void main(String[] args) {

		ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
				"classpath:/applicationContext.xml");

		Repository repository = context.getBean(CRUDImplementation.class);

		// cleanup collection before insertion
		repository.dropCollection();

		// create collection
		repository.createCollection();

		repository.saveObject(new Employee("1", "Jerry", "Jacob", 30));
	}
Tagged with: , , , ,

Making your Spring application, ‘Context Aware’

Posted in Java/ J2EE by jerlinworld on July 20, 2009

Suppose you have some java classes which are unable (or you don’t want it) to be wired to the Spring application context; for example, an auto generated web service client class! But you do want to use the dependency injection feature of Spring to get some of the other beans injected in to this class. How can we make this happen? One way to achieve this would be to use the ApplicationContextAware interface provided by Spring.

Create a class named ApplicationContext which implements  ApplicationContextAware. The inherited method, ‘setApplicationContext(…)’ will get called during the creation of this bean, providing the reference to the context. Our program should store this for a later interaction with the context.

package jerry.jacob;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextProvider implements ApplicationContextAware {
    private static ApplicationContext ctx = null;
    public static ApplicationContext getApplicationContext() {         
        return ctx;    
    }
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        // Assign the ApplicationContext into a static method
        this.ctx = ctx;
    }
}

Initialize the new bean in applicationContext.xml

<bean id="applicationContextProvider" class="jerry.jacob.ApplicationContextProvider"></bean>

Now you can call the static method, getApplicationContext(), from any class in your application, to get assess to the Spring ApplicationContext.