Spring Data MongoDB Integration

Spring Data MongoDB hello world example
In this tutorial, we show you how to do configure (both XML and annotation) and perform CRUD operations with “Spring Data for MongoDB” framework.

Tools and technologies used :

    Spring Data MongoDB – 1.0.0.M2
    Spring Core – 3.0.5.RELEASE
    Java Mongo Driver – 2.5.2
    Eclipse – 3.6
    JDK – 1.6
    Maven – 3.0.3
1. Dependency(pom.xml)

<project ...>
	<repositories>
		<repository>
			<id>spring-milestone</id>
			<name>Spring Maven MILESTONE Repository</name>
			<url>http://maven.springframework.org/milestone</url>
		</repository>
	</repositories>
 
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.8.2</version>
			<scope>test</scope>
		</dependency>
 
		<!-- Spring framework -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>3.0.5.RELEASE</version>
		</dependency>
 
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.0.5.RELEASE</version>
		</dependency>
 
		<!-- mongodb java driver -->
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>2.5.2</version>
		</dependency>
 
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-mongodb</artifactId>
			<version>1.0.0.M2</version>
		</dependency>
 
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2</version>
		</dependency>
 
	</dependencies>
 
</project>


2.Two ways to configure Spring data for MongoDB.
Annotation

To use Spring annotation, declare the Spring mongoDB detail in a Java file :

File : SpringMongoConfig.java

package com.mkyong.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.document.mongodb.MongoTemplate;
import org.springframework.data.document.mongodb.config.AbstractMongoConfiguration;
import com.mongodb.Mongo;
 
/**
 * Spring MongoDB configuration file
 * 
 */
@Configuration
public class SpringMongoConfig extends AbstractMongoConfiguration {
 
	@Override
	public @Bean Mongo mongo() throws Exception {
 
		return new Mongo("localhost");
	}
 
	@Override
	public @Bean MongoTemplate mongoTemplate() throws Exception {
 
		return new MongoTemplate(mongo(),"yourdb","yourCollection");
	}
 
}


And include it with Spring’s AnnotationConfigApplicationContext :

ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
    MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");



XML

To use Spring XML, declare the Spring mongoDB detail in a XML file :

<?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">
 
	<!-- Default bean name is 'mongo' -->
	<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="yourdb" />
		<constructor-arg name="defaultCollectionName" value="yourCollection" />
	</bean>
 
	<!-- To translate any MongoExceptions thrown in @Repository annotated classes -->
	<context:annotation-config />
 
</beans>


And include it with Spring’s AnnotationConfigApplicationContext :

 ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
    ApplicationContext ctx = new GenericXmlApplicationContext("mongo-config.xml");



3. User Model

An User object, later use Spring data to bind this object to / from MongoDB.

File : User.java

package com.mkyong.user;
 
public class User {
 
	private String id;
	private String firstname;
	private String lastname;
	private int age;
 
	//getter and setter methods 
}


4. CRUD Operations

Full example to show you how to use Spring data to perform CRUD operations in mongoDB. The “user” object is saved into a collection named “userprofile“, under “yourdb” database.

The Spring data APIs are quite clean and should be self-explanatory.
Note
MongoTemplate implemented MongoOperations interface.
File : App.java

package com.mkyong.core;
 
import java.util.List;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
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 org.springframework.data.document.mongodb.query.Update;
import com.mkyong.config.SpringMongoConfig;
import com.mkyong.user.User;
 
public class App
{
 
    public static void main( String[] args )
    {
    	//For Annotation
    	ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
 
    	//For XML
    	//ApplicationContext ctx = new GenericXmlApplicationContext("mongo-config.xml");
 
    	MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");
 
        User user = new User("1001", "yong", "mook kim", 30);
 
        //save
        mongoOperation.save("userprofile",user);
 
        //find
        User savedUser = mongoOperation.findOne("userprofile",
        		new Query(Criteria.where("id").is("1001")),
				User.class);
 
        System.out.println("savedUser : " + savedUser);
 
        //update
        mongoOperation.updateFirst("userprofile",
        		new Query(Criteria.where("firstname").is("yong")), 
        		Update.update("lastname", "new lastname"));
 
        //find
        User updatedUser = mongoOperation.findOne("userprofile",
        		new Query(Criteria.where("id").is("1001")),
				User.class);
 
        System.out.println("updatedUser : " + updatedUser);
 
        //delete
        mongoOperation.remove("userprofile",
        		new Query(Criteria.where("id").is("1001")),
        		User.class);
 
        //List
        List<User> listUser =  
        	mongoOperation.getCollection("userprofile", User.class);
        System.out.println("Number of user = " + listUser.size());
 
    }
 
}


5:Output

savedUser : User [id=1001, firstname=yong, lastname=mook kim, age=30]
updatedUser : User [id=1001, firstname=yong, lastname=new lastname, age=30]
Number of user = 0

 

 

你可能感兴趣的:(Spring Data MongoDB Integration)