`
elicer
  • 浏览: 133346 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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:Spring Data Modern Data Access for Enterprise Java

    Part I. Background 1. The Spring Data Project ...13. Creating Big Data Pipelines with Spring Batch and Spring Integration Part VI. Data Grids 14. GemFire: A Distributed Data Grid Bibliography Index

    Java Spring-data for mongodb

    - `pentaho-mongodb-plugin-5.0.5.jar`:这是一个Pentaho Data Integration (Kettle)的MongoDB插件,用于ETL(提取、转换、加载)操作。 - `ojdbc14.jar` 和 `spring-jdbc-3.2.4.RELEASE.jar`:尽管这些是针对...

    spring data 示例

    7. **Integration with Spring Boot**: Spring Boot与Spring Data结合,可以提供开箱即用的数据访问配置,大大简化了设置过程。开发者只需在`application.properties`中添加必要的配置,就可以启动和运行数据库连接...

    spring-data-commons1.50

    Spring Data 的目标是简化数据库访问,并通过一致的编程模型和方法来增强现代数据存取技术,如关系型数据库、NoSQL 数据库(如 MongoDB)和其他持久层服务。 在 `spring-data-commons-1.5.0.RELEASE` 这个版本中,...

    data-integration-spring-mongo:使用Spring和MongoDB集成csv数据的项目

    java -jar data-integration-1.0.jar REST服务已创建: localhost:8080/companies/loader localhost:8080/companies/integrator localhost:8080/companies/search?name=DIRECTV&zip=38006 在搜索中,两个都必须...

    SpringData视频教程相关源代码和PPT

    7. **Integration with Spring Boot**:SpringBoot的自动化配置与SpringData的结合,使得开发者可以快速搭建数据访问层,无需繁琐的配置。 8. **Paging and Sorting**:SpringData提供了分页和排序的功能,使得大...

    Spring Data简介

    **Spring Data 概述** Spring Data 是一个广受欢迎的开源框架,它简化了与数据库的交互,特别是对于Java开发者而言。这个框架的核心目标是通过提供一个一致的编程模型和简单的API来减少数据访问层的复杂性,使得...

    spring-data-commons-1.3.1

    5. **Integration with Spring**:Spring Data Commons紧密集成于Spring框架,可以无缝地利用Spring的事务管理、AOP切面以及依赖注入等功能。这使得整个应用的架构更加清晰,提高了代码的可维护性和测试性。 6. **...

    spring-5.0.5.rar

    在数据访问层,Spring Data JPA和Spring Data MongoDB等项目在5.0.5版本中继续优化了对现代数据库的集成。例如,对JPA的增强包括了更好的查询构造器和对多数据源的支持。对于NoSQL数据库,Spring Data MongoDB提供了...

    SpringBoot+MongoDB+Maven,非常实用的入门资料,使用tomcat启动!

    3. MongoDB的基本操作:了解MongoDB的数据模型,如何连接MongoDB数据库,使用Spring Data MongoDB进行数据操作。 4. RESTful API的开发:利用SpringBoot的@RestController注解创建RESTful服务,提供HTTP接口供...

    spring.zip

    1. **Spring Data**: Spring Data是一个致力于简化数据访问开发的项目,它支持多种数据存储技术,如关系型数据库(JPA、Hibernate)、NoSQL(MongoDB、Cassandra)和图数据库(Neo4j)。Spring Data提供了一致的API...

    Spring Framework v6.1.4.zip

    例如,Spring Data JPA使得与JPA供应商(如Hibernate)的集成变得简单,而Spring Data MongoDB则为MongoDB提供了类似的便利。 此外,Spring Security提供了全面的安全管理功能,包括身份验证、授权和安全配置,确保...

    spring-data-commons-1.3.0.M1.zip

    5. **Integration with Various Data Stores**:Spring Data Commons与多种数据存储系统兼容,包括关系数据库(JPA、Hibernate)、NoSQL数据库(MongoDB、Cassandra)、图数据库(Neo4j)等,使得跨平台和跨数据源的...

    spring4.x________

    2. 模块化:Spring框架由多个模块组成,如Core Container、Data Access/Integration、Web等,可以根据项目需求选择合适的模块,避免不必要的重量级引入。 3. 容器管理:Spring容器负责初始化、配置和管理Bean,简化...

    Spring开发指南v0.8

    Spring Data JPA和Spring Data MongoDB等项目进一步扩展了对NoSQL数据库的支持,使得数据访问更加统一和便捷。 此外,Spring MVC是Spring框架中的Web MVC实现,它为构建高性能、可测试的Web应用程序提供了全面的...

    mongodb52demo.zip

    在项目中,你可能还会发现`Spring Data MongoDB`的使用,这是一个非常流行的框架,简化了与MongoDB的集成。通过定义Repository接口,你可以直接在Java代码中使用方法名来执行查询,如`findAll`, `findById`, 或...

    精通Spring开发专家之Sun ONE-1

    5. **Spring Data访问**:理解Spring Data对JDBC、ORM框架(如Hibernate、MyBatis)的支持,以及Spring Data JPA和Spring Data MongoDB等NoSQL数据存储的集成。 6. **Spring Boot**:学习Spring Boot的自动配置、...

    java spring 开发

    同时,Spring Data JPA和Spring Data MongoDB等项目进一步简化了NoSQL数据库的集成。 Spring_Live1-11.pdf很可能包含了Spring框架的详细教程或者实战指南,涵盖了Spring的核心概念、配置、MVC、AOP、事务管理、数据...

    spring-data:测试项目spring数据

    7. **Integration 测试**:在测试项目中,Spring Data 提供了丰富的测试工具和辅助类,如 `MongoTemplate` 和 `JdbcTemplate`,可以帮助开发者编写针对数据访问层的单元测试和集成测试,确保数据访问的正确性。...

Global site tag (gtag.js) - Google Analytics