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

Spring整合mongodb详解

一、前言

  1. MongoDB 是一个可扩展的、高性能的、开源的NoSQL数据库,跟传统的数据库不一样,MongoDB并不是将数据存储在表中,他将数据结构化为一个类似于JSON的文档中。这篇文章就是展示如何使用Java基于MongoDB和Spring Data创建一个CRUD应用。
  2. Spring Data for MongoDB ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??Spring Data for MongoDB提供了一个类似于基于Sping编程模型的NoSQL数据存储。Spring Data for MongoDB提供了很多特性,它使很多MongoDB的Java开发者解放了很多。MongoTemplate helper类支持通用的Mongo操作。它整合了文档和POJO之间的对象映射。通常,他会转换数据库访问异常到Spring中的异常结构。使用起来非常的方便。

MongoDB的API提供了DBObject接口来实现BSONObject的操作方法,BasicDBObject是具体实现。但是并没有提供DBObjectBeanObject的转换。

代码要处理Bean中的各种类型,并且要控制持久化时的深度:

  • 基础类型(int, float, boolean...)
  • 基础扩展类型(Integer, Float, Boolean)
  • 枚举
  • ObjectId
  • 普通对象 extends Object
  • 业务对象(拥有ObjectId的对象)
  • 容器List, Map, Set(处理元素时要把上面的类型再处理一遍)

以上这些东西,spring-data-mongo ?都可以实现

参考质料 ?

  • http://projects.spring.io/spring-data-mongodb/
  • http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/
  • http://docs.mongodb.org/manual/core/introduction/
  • spring官方提供的整合mongodb ? ? ?spring-data-mongodb-reference.pdf

?本项目是亲测过的

二、项目

  1. 所依赖的jar包 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ???? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

  2. ?spring的配置文件? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?applicationContext.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.springframework.org/schema/data/mongo"
    	xsi:schemaLocation="http://www.springframework.org/s