论坛首页 Java企业应用论坛

Spring Data MongoDB Integration

浏览 3250 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (1)
作者 正文
   发表时间:2011-12-04  

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 :

  1. Spring Data MongoDB – 1.0.0.M2
  2. Spring Core – 3.0.5.RELEASE
  3. Java Mongo Driver – 2.5.2
  4. Eclipse – 3.6
  5. JDK – 1.6
  6. Maven – 3.0.3

1. Project Structure

A classic Maven style Java project directory structure.

Spring data for mongodb directory structure

2. Dependency

To develop Spring data for MongoDB, you need following libraries :

spring-data-mongodb
Currently, the “spring-data-mongodb ” jar is only available in “http://maven.springframework.org/milestone “, so, you have to declare this repository also.

File 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>


3. Spring Configuration

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"
)
;

4. 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 

}

5. 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
(
)
)
;

 
    }

 
}

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
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics