Quantcast
Channel: HMKCode » mongodb
Viewing all articles
Browse latest Browse all 5

Mongodb + Spring Data (to the point)

0
0

Using POJO as a centric data model for interacting with mongodb, can be achieved with Spring Data.

Objectives:

  • Building simple mongodb java application using Spring Data.

Environment:

Libraries:

for complete list of jar files check .classpath file with the source code

for complete pom.xml file check source code

<dependencies>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>
        <version>1.1.1.RELEASE</version>
    </dependency> 
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.1.1</version>
        <scope>runtime</scope>
    </dependency>              
  </dependencies>

( 1 ) Project Structure

( 2 ) Spring Configuration (xml configuration)

Note: you can configure Spring Data Mongodb using annotation “Java based bean metadata” 5.3.1 Registering a Mongo instance using Java based metadata.

  • spring.xml

for complete spring.xml file check the source code

<?xml version="1.0" encoding="UTF-8"?>
<beans .....

    <!-- Default bean name is 'mongo' -->
    <mongo:mongo host="localhost" port="27017"/>

    <!-- Default bean name is 'mongoDbFactory' -->
    <mongo:db-factory dbname="test" />

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

	<!-- Alternative way to instantiate mongoTemplate
		<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    		<constructor-arg ref="mongo"/>
	    	<constructor-arg name="databaseName" value="test"/>
  		</bean>
	-->
</beans>

( 3 ) POJO

We have two java model “POJO” that will be stored in mongodb as documents.

  • Person.java: main data model to be stored as “document”.
  • Address.java: will be stored as sub document of Person.
  • @Document(collection=”people”) : if collection is declared here no need to specify it when applying CRUD to Person.
  • Person.java
package com.hmkcode.vo;

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

@Document(collection="people")
public class Person {

	//Field annotated with "@Id" or named "id" will be mapped to document _id which is a required field.
	//so here we can add @Id or leave it.
	@Id
	private int id;
	private String name;
	private String[] friends;
	private Address address;

	public Person(int id,String name,String[] friends,Address address){
		this.id = id;
		this.name = name;
		this.friends = friends;
		this.address = address;
	}
	//instantiate Person with default friends and address
	public Person(int id,String name){
		this.id = id;
		this.name = name;
		String f[] = {"John","Brit","Tim"};
		this.friends = f;
		this.address = new Address("US","NY","New York");
	}
	public Person(){}

      //setters and getters...

	public String toString(){
		String friendsArray = "";
		for(int f = 0 ; f < friends.length;f++)
			friendsArray += friends[f]+( (f+1) < friends.length?" , ":"");

		return "{id: "+this.id+", name: "+this.name+", friends: [ "+friendsArray+" ] , address: "+this.address+"}";
	}
}
  • Address.java
package com.hmkcode.vo;

public class Address {

	private String country;
	private String state;
	private String city;

	public Address(String country,String state,String city){
		this.country = country;
		this.state = state;
		this.city = city;
	}

	public Address(){}

	//setters & getters...

	public String toString(){
		return "{country: "+this.country+" , state: "+this.state+" , city: "+this.city+"}";
	}
}

( 4 ) Interacting with Mongodb (Main.java)

  1. save(Person) “only one”
  2. insert(Collection<Person>) “many person”
  3. find(Person where name =”Scott”)
  4. findAll(Person.class)
  5. updateMulti(Person set address ={country: US , state: CA , city: San Diego} where name = “Scott”)
  6. find(Person where name =”Scott”)
  7. remove(Query,Person.class)
  • Main.java
package com.hmkcode.spring.data.mongodb;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.mapping.Document;
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.hmkcode.vo.Address;
import com.hmkcode.vo.Person;

public class Main {

	public static void main(String args[]){

		ApplicationContext ctx = new ClassPathXmlApplicationContext("com/hmkcode/spring/spring.xml");
		MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");

		Collection<Person> persons = new LinkedList<Person>();
		persons.add(new Person(2,"Scott"));
		persons.add(new Person(3,"Tim"));
		persons.add(new Person(4,"Lora"));

		//( 1 ) save one person
		// if collection is not specified in @Document(collection="people"), we need to specify collection name 
		// in save(document, collection);
		mongoOperation.save(new Person(1,"Brit"));
		//-------------------------------------------------------

		//( 2 ) insert many persons
		//if we have a list of different type of documents to be inserted, their collection will be 
		//specified by @Document(collection="collectionName")
		mongoOperation.insert(persons, Person.class);

		//-------------------------------------------------------
		//( 3 ) find inserted person
		Person savedPerson = mongoOperation.findOne(
					new Query(Criteria.where("name").is("Scott")), 
					Person.class
			        );

		System.out.println("saved Person: " + savedPerson);
		//-------------------------------------------------------
		//( 4 ) find all persons
		List<Person> allPersons = mongoOperation.findAll(Person.class);

		System.out.println("Number of persons = " + allPersons.size());
		//-------------------------------------------------------
		//( 5 ) updateMulti
		 // update
		  mongoOperation.updateMulti(
			new Query(Criteria.where("name").is("Scott")),
	        Update.update("address", new Address("US","CA","San Diego")),
	        Person.class
	     );
		//-------------------------------------------------------
		//( 6 ) find updated person
		Person updatedPerson = mongoOperation.findOne(
						new Query(Criteria.where("name").is("Scott")), 
						Person.class
				        );

		System.out.println("Updated Person: " + updatedPerson);
		//-------------------------------------------------------
		//( 7 ) remove person
		mongoOperation.remove(new Query(),Person.class);

		System.out.println("Numober persons: " + mongoOperation.findAll(Person.class).size());
	}
}

( 5 ) Run

  • Run mongodb
  • Run Main.java

You should get the following results

Source Code github


Viewing all articles
Browse latest Browse all 5

Latest Images

Trending Articles





Latest Images