日期:2014-05-16  浏览次数:20448 次

Spring Data MongoDB hello world 示例

?

下面讲解如何使用spring-data-mongdb来对mongdb进行增删改查的操作

?

你需要的工具:

?

  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.工程目录结构
? ??Spring data for mongodb directory structure

2.依赖
? ?你需要在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的配置

? ?可以通过两种方式来配置spring data来使用mongodb

Annotation

?需要在java文件中声明spring的mongodb注解

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

?

?然后在main函数中就可以通过下面方式来获取mongodbtemplate

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

?

XML

? ?通过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"
	xmlns:mongo="http://www.springframewor