分类目录归档:MongoDB

MongoDB是一个基于分布式文件存储的数据库。

User Spring And Hibernate With MongoDB


The first thing to do is to install MongoDB on your machine (unfortunately it is not yet possible to run it embedded so we use a local instance instead). For installation see this.One of the requirements we have for one of our Mule ESB implementations is to log the messages that went through the ESB (especially handy during development and testing). There has been written a lot already about logging with Mule so I am not going to discuss that again. In this post I’ll only show you how you can use Spring/Hibernate and MongoDB to store your messages in the MongoDB, because a document-oriented database like MongoDB is a nice fit for this requirement.

After MongoDB is installed we can create a new standard Maven project and modify the generated pom.xml to the following pom.xml.

Next step is the creation of the Hibernate Entity class like this: 

package nl.redstream.mongo.entity;
 
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.bson.types.ObjectId;
 
/**
 * Model object 
 * @author pascal
 */
@Entity
@Table(name = "logItems")
public class LogItem implements Serializable {
 
    @Id
    private ObjectId id;
    private String message;
    private String timestamp;
 
    public ObjectId getId() {
        return id;
    }
 
    public void setId(ObjectId id) {
        this.id = id;
    }
 
    public String getMessage() {
        return message;
    }
 
    public void setMessage(final String message) {
        this.message = message;
    }
 
    public String getTimestamp() {
        return timestamp;
    }
 
    public void setTimestamp(final String timestamp) {
        this.timestamp = timestamp;
    }
 
    @Override
    public String toString() {
        return "LogItem [id=" + id + ", message=" + message + ", timestamp=" + timestamp + "]";
    }
}

As you might notice I have used the ObjectId as primary Id. I was forced to this by bug DATADOC-176 which only recently got fixed.

The Dao and Service object classes that are used to access the MongoDB are:

Now wire this all together with the following spring config files:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation=
               "http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
    <import resource="spring-mongodb-config.xml"/>
 
    <bean id="logService" class="nl.redstream.mongo.services.MongoDBLoggerServiceImpl">
        <property name="dao" ref="logDao"/>
    </bean>
    <bean id="logDao" class="nl.redstream.mongo.dao.LogItemDaoImpl">
        <property name="mongoTemplate" ref="mongoTemplate"/>
    </bean>
</beans>

and the ‘spring-mongodb-config.xml’ (as described here):

<?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:mongo="http://www.springframework.org/schema/data/mongo"
       xsi:schemaLocation=
               "http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                http://www.springframework.org/schema/data/mongo
                http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
 
    <!-- Default bean name is 'mongo' -->
    <mongo:mongo host="localhost" port="27017">
        <!-- OPTIONAL: configure <mongo:options /> -->
    </mongo:mongo>
 
    <mongo:db-factory dbname="redstream" mongo-ref="mongo"/>
 
    <bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate">
        <constructor-arg ref="mongoDbFactory"/>
    </bean>
</beans>

That’s it. Now you have a foundation to start using MongoDB with Spring and Hibernate classes. In the next post I will show how you can test this setup without manually having to start and stop MongoDB.This article comes from:http://www.redstream.nl/2011/07/14/use-spring-and-hibernate-with-mongodb/

使用 Morphia 和 MongoDB 实现域模型持久性

使用 Morphia 持久保存、加载、删除和查询映射到 MongoDB 的 Java 域模型

John D’Emic, 高级软件工程师, IBM

简介: MongoDB 是面向文档的开源数据库,Morphia 是面向 MongoDB 的类型安全的对象映射库。本文解释了在文档和对象之间进行映射的好处,并演示了如何使用 Morphia 来实现这个功能。然后演示了如何持久保存、加载、删除和查询映射到 MongoDB 的 Java™ 域模型。

MongoDB 是面向文档的数据库,用于存储并检索类似 JavaScript 对象符号(JavaScript Object Notation,JSON)的文档。由于索引、复制和分片功能的增强,MongoDB 已成为强大的、可扩展的 NoSQL 竞争者(参见 参考资料)。

官方 Java 驱动程序可用于与 MongoDB 交互。该驱动程序提供 Map 的实现 BasicDBObject,用于在数据存储中表示文档。虽然 Map 表示法很方便,尤其是在读对 JSON 序列化和反序列化时,但是能够将文档表示为 Java 类层次也具有其优点。例如,反复从 Java 域模型映射文档,允许您在 Java 层上强行执行类型安全,同时通过 MongoDB 享受无模式(schema)开发的好处。

Morphia 是基于 Apache 许可证的 Google Code 项目,让您在 MongoDB 上持久保存、检索、删除和查询作为文档存储的 POJO。通过提供一系列围绕 Mongo Java 驱动程序的注释和包装程序,Morphia 完成了这些操作。Morphia 概念上类似于对象关系映射器(ORM),如 Java Persistence API (JPA) 或 Java 数据对象(Java Data Objects,JDO)实现。在本文中,我将演示如何对映射到 MongoDB 的 Java 域模型使用 Morphia。参见 下载 部分获取完整的样例代码。

定义域模型

我将使用简化的域模型来演示 Morphia 的功能。BandManager(假想的 web 应用程序)提供有关音乐活动的数据:其成员、经销商、目录、类型等等。我将定义 BandSongDistributor 和 ContactInfo 类来表示此域模型,如图 1 所示:



图 1. BandManager 的类

针对 BandManager 应用程序的域模型类层次的 UML 图表 

图 1 中的统一建模语言(Unified Modeling Language,UML)显示了域模型类层次。左侧的矩形表示 Band 类。右侧的矩形分别表示ContactInfoDistributor 和 Song 类。从 Band 指向 ContactInfo 的箭头在 ContactInfo 旁边标有一个 1,这说明两个类之间是一对一的关系。连接 Band 到 Distributor 的线在 Band 旁边标有 0..* 且在 Distributor 旁边标有一个 1,这说明 Band 具有单一的Distributor 且 Distributor 表示许多 Band。最后,从 Band 到 Song 的箭头在 Song 旁边标有目录 0..1,这说明 Band 具有与 Song 的一对多关系且这种关系被称作 catalog

我将对这些类进行注释,然后使用 Morphia 的 Datastore 接口在 MongoDB 上将它们保存为文档。

注释域模型

清单 1 显示了如何注释 Band 类:



清单 1. Band.java 

				
@Entity("bands")
public class Band {

    @Id
    ObjectId id;

    String name;

    String genre;

    @Reference
    Distributor distributor;

    @Reference("catalog")
    List<Song> songs = new ArrayList<Song>();

    @Embedded
    List<String> members = new ArrayList<String>();

    @Embedded("info")
    ContactInfo info;


@Entity 注释是必需的。其声明了在专用集合(collection)上该类作为文档将持久保存。提供给 @Entity 注释的值(bands)定义了如何命名集合。在默认情况下,Morphia 使用类名称来命名集合。例如,如果我遗漏了 bands 值,则在数据库中该集合将被称为Band

数据类型

MongoDB 比 Java 语言支持更小的数据类型集合,即integerlongdouble 和 string。Morphia 可自动为您转换基本 Java 类型(如 float)。

@Id 注释指示 Morphia 哪个字段用作文档 ID。如果您试图持久保存对象(其 @Id 注释的字段为 null),则 Morphia 会为您自动生成 ID 值。

Morphia 试图持久保存每一个它遇到的没有注释的字段,除非它们标有@Transient 注释。例如,在文档中 name 和 genre 属性将被保存为string,并具有 name 和 genre 键。

distributorsongsmembers 和 info 属性引用其他对象。除非注释有@Reference(不久将看到),否则成员对象将被视为嵌入的(embedded)。它会显示为集合中父文档的子集。例如,在持久保存时,members List 看上去如下所示:

"members" : [ "Jim", "Joe", "Frank", "Tom"]


info 属性是另外一个嵌入的对象。在本例中,我通过 info 值明确地设置 @Embedded 注释。这会覆盖文档中子集的默认命名,否则就会被称为 contactInfo。例如:

"info" : { "city" : "Brooklyn", "phoneNumber" : "718-555-5555" }


@Reference 和 DBRefs

在后台,Morphia 使用 Mongo DBRef 来在不同集合中引用对象。

使用 @Reference 注释说明对象是对另外一个集合中的文档的引用。在从 Mongo 集合中加载对象时,Morphia 遵循着这些引用来建立对象图。例如,在持久保存的文档中,distributor 属性看起来如下所示:

"distributor" : { "$ref" : "distributors", "$id" : ObjectId("4cf7ba6fd8d6daa68a510e8b") }


正如 @Embedded 注释一样,@Reference 可以采用一个值来覆盖默认命名。在本例中,我将 songs 的 List 称为文档中的 catalog

现在看一下 SongDistributor 和 ContactInfo 的类定义。清单 2 显示了 Song 的定义:



清单 2. Song.java 

				

@Entity("songs")
public class Song {

    @Id
    ObjectId id;

    String name;


清单 3 显示了 Distributor 的定义:



清单 3. Distributor.java 

				

@Entity("distributors")
public class Distributor {

    @Id
    ObjectId id;

    String name;

    @Reference
    List<Band> bands = new ArrayList<Band>();


清单 4 显示了 ContactInfo 的定义:



清单 4. ContactInfo.java

				
public class ContactInfo {


    public ContactInfo() {
    }

    String city;

    String phoneNumber;


ContactInfo 类缺少 @Entity 注释。这是故意而为的,因为我不需要 ContactInfo 的专用集合。实例总是被嵌入 band 文档。

现在我已经定义并注释了域模型,我将向您展示如何使用 Morphia 的 Datastore 以便保存、加载和删除实体。

使用 Datastore

依赖注入(Dependency injection,DI)

Datastore 和 Mongo 都是 DI 友好型。例如,在 Spring 或 Guice 中,您不应该在连接它们的问题上遇到任何麻烦。如果有可能,您应该配置每一个作为单一实例并在合作(collaborating)bean 之间共享它们。

Datastore 接口 — Mongo Java 驱动程序的包装程序 — 用于在 MongoDB 中管理实体。因为 Datastore 需要 Mongo 实例以进行实例化,您可以重新使用现有的 Mongo 实例或为您的环境适当地配置一个实例。下面是一个实例化 Datastore 的示例,其连接到本地 MongoDB 实例:

Mongo mongo = new Mongo("localhost");
Datastore datastore = new Morphia().createDatastore(mongo, "bandmanager");


下一步我将创建 Band 实例:

Band band = new Band();
band.setName("Love Burger");
band.getMembers().add("Jim");
band.getMembers().add("Joe");
band.getMembers().add("Frank");
band.getMembers().add("Tom");
band.setGenre("Rock");


现在我拥有了 Band 实例,我可以使用 datastore 来持久保存它:

datastore.save(band);


band 现在应该保存在 bandmanager 数据库中被称为 bands 的集合中。通过使用 Mongo 命令行界面客户端,我可以查看一下以便确保(在本示例和其他示例中,折行以便适合本文页面的宽度):

> db.bands.find();
{ "_id" : ObjectId("4cf7cbf9e4b3ae2526d72587"), "className" : 
"com.bandmanager.model.Band", "name" : "Love Burger", "genre" : "Rock", 
"members" : [ "Jim", "Joe", "Frank", "Tom" ] }


这真是太棒了!它就在这里。除了 className 字段以外,一切看起来正如您所期望的。Morphia 自动创建此字段以便记录 MongoDB 中的对象类型。其主要用于确定在编译时不必知道的对象类型(例如,在您从具有混合类型的集合中加载对象时)。如果这个困扰了您且您知道您不需要该功能,那么通过将 noClassnameStored 值添加到 @Entity 注释,您可以禁用持久保存 className

@Entity(value="bands",noClassnameStored=true)


现在我将加载 Band 并断言它等同于我所持久保存的 band

assert(band.equals(datastore.get(Band.class, band.getId())));


Datastore 的 get() 方法允许您使用实体的 ID 加载该实体。您无需指定集合或定义查询字符串来加载对象。您只需告诉 Datastore ,您想加载哪个类及其 ID。Morphia 进行其余的操作。

现在可以查看 Band 的合作对象了。我开始先定义一些 Song,然后将它们添加到我刚刚创建的 Band 实例:

Song song1 = new Song("Stairway");
Song song2 = new Song("Free Bird");

datastore.save(song1);
datastore.save(song2);


如果我在 Mongo 中查看 songs 集合,我应该看到如下所示:

> db.songs.find();
{ "_id" : ObjectId("4cf7d249c25eae25028ae5be"), "className" : 
"com.bandmanager.model.Song", "name" : "Stairway" }
{ "_id" : ObjectId("4cf7d249c25eae25038ae5be"), "className" :
"com. bandmanager.model.Song", "name" : "Free Bird" }


请注意 Song 还没有从 band 引用。我将它们添加到 band 并查看发生了什么:

band.getSongs().add(song1);
band.getSongs().add(song2);

datastore.save(band);


现在我查询 bands 集合时,我应该看到:

{ "_id" : ObjectId("4cf7d249c25eae25018ae5be"), "name" : "Love Burger", "genre" : "Rock", 
   "catalog" : [
   {
      "$ref" : "songs",
      "$id" : ObjectId("4cf7d249c25eae25028ae5be")
   },
   {
      "$ref" : "songs",
      "$id" : ObjectId("4cf7d249c25eae25038ae5be")
   }
], "members" : [ "Jim", "Joe", "Frank", "Tom"] }


事务

非常重要的是记住 MongoDB 不像大多数关系数据库管理系统那样支持事务。如果您的应用程序需要协调多个线程写入或读取集合,您就必须依靠 Java 语言的序列化和并发功能。

请注意 songs 集合如何被保存为一个被称为 catalog 的数组,作为两个DBRef

现在的限制是引用的对象必须先被保存,然后其他对象才能引用它们。这解释了为什么我先保存 song1 和 song2,然后将它们添加到 band

现在我将删除 song2

datastore.delete(song2);


查询 songs 集合应该说明没有了 song2。但是如果您查看 band,您将看到该歌曲仍在那里。更糟糕的是,试图加载 band 实体会导致异常:

Caused by: com.google.code.morphia.mapping.MappingException: The 
reference({ "$ref" : "songs", "$id" : "4cf7d249c25eae25038ae5be" }) could not be 
fetched for com.bandmanager.model.Band.songs


现在,要避免此错误,您需要在删除歌曲以前手动删除对它的引用。

查询

到目前为止,通过其 ID 加载实体只能得到实体的信息。最终我希望能够查询 Mongo 并得到我想要的实体。

我将通过名称查询 band,而不是通过其 ID 加载它。为此,我通过创建 Query 对象并指定筛选器来获得我希望的结果:

Query query = datastore.createQuery(Band.class).filter("name = ","Love Burger");


我指定了想要查询的类,即 Band,和针对 createQuery() 方法的筛选器。一旦我定义了查询,我就可以使用 asList() 方法来访问结果:

Band band = (Band) query.asList().get(0);


Morphia 的筛选运算符紧密地映射到用于 MongoDB 查询的查询运算符。例如,我在上面查询中使用的 = 运算符就类似于 MongoDB 中的 $eq 运算符。有关筛选运算符的全部细节都在 Morphia 在线文档中(参见 参考资料)。

作为筛选查询的替代,Morphia 为构建查询提供了更好的接口。例如,以下接口查询等同于以前的筛选查询:

Query query = datastore.createQuery(Band.class).field("name").equal("Love Burger");


您可以使用“点注释”来查询嵌入的对象。下面是使用点注释和接口的查询,用于选择位于 Brooklyn 的所有乐队:

Query query = datastore.createQuery(Band.class).field("info.city").equal("Brooklyn");


您可以进一步定义查询结果集。我将修改以前的查询以便根据名称来对乐队排序并将结果限制为 100:

Query query = 
datastore.createQuery(Band.class).field("info.city").equal
("Brooklyn").order("name").limit(100);


索引

您将注意到随着您的集合增长查询性能将会降低。Mongo 集合(非常像关系数据库表)需要正确进行索引以便确保合理的查询性能。

通过 @Indexed 注释对属性进行注释会对该字段应用索引。这里,我对 Band 的 genre 属性创建了一个名为 genreName 的升序索引:

@Indexed(value = IndexDirection.ASC, name = "genreName")
String genre;


要应用索引,Morphia 需要知道映射哪些类。您需要以稍微不同的方式实例化 Morphia 以便确保应用索引。您可以按如下所示执行:

Morphia morphia = new Morphia();
morphia.mapPackage("com.bandmanager.model");
datastore = morphia.createDatastore(mongo, "bandmanager");
datastore.ensureIndexes();


最终的 ensureIndexes() 调用可以指示数据存储创建所需且不存在的索引。

索引还可用于避免将重复项插入到集合中。例如,通过在 band 名称的 @Indexed 注释上设置 unique 属性,我可以确保在该集合中只有一个具有给定名称的 band

@Indexed(value = IndexDirection.ASC, name = "bandName", unique = true)
String name;


随后同名的 band 将被丢弃。

结束语

Morphia 是与 MongoDB 进行交互的强大工具。它允许对 MongoDB 文档进行类型安全的、惯用的访问。本文涵盖了使用 Morphia 的主要方面,但排除了一些功能。要获得有关其数据访问对象(Data Access Object,DAO)支持、验证和手动映射功能的信息,我鼓励您查看 Morphia Google Code 项目。


下载

描述 名字 大小 下载方法
本文样例代码 j-morphia.zip 17.2KB HTTP

关于下载方法的信息


参考资料

学习

获得产品和技术

讨论

关于作者

/developerworks/i/p-jdemic.jpg

John D’Emic 是 IBM Global Services 的高级软件工程师且在过去的一年中在各种不同的开发环境中使用了 MongoDB。他是 Mule in Action(Manning Publications,2009 年)(与 David Dossot)的合著者。

This article comes from :http://www.ibm.com/developerworks/cn/java/j-morphia/index.html?ca=drs-

Spring & MongoDB初试

最近在学习Spring和MongoDB的结合,在Spring官网下载了Spring Data MongoDB hello world example 例子,配置过程种出现各种错误。和大家分享下,有兴趣的可以一起研究下:

错误一:
Exception in thread “main” java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.springframework.context.support.AbstractApplicationContext.<init>

(AbstractApplicationContext.java:160)
at org.springframework.context.support.AbstractApplicationContext.<init>

(AbstractApplicationContext.java:213)
at org.springframework.context.support.GenericApplicationContext.<init>(GenericApplicationContext.java:101)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>

(AnnotationConfigApplicationContext.java:63)
at com.mkyong.core.App.main(App.java:21)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
… 5 more
这是因为缺少包commons-logging-1.1.1.jar把包加入项目问题就解决了。

错误二:
如果你运行的是//For Annotation
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
出现如下错误:
Exception in thread “main” java.lang.IllegalStateException: Cannot load configuration class: 

com.mkyong.config.SpringMongoConfig
at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses

(ConfigurationClassPostProcessor.java:246)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanFactory

(ConfigurationClassPostProcessor.java:160)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors

(AbstractApplicationContext.java:663)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors

(AbstractApplicationContext.java:602)
at org.springframework.context.support.AbstractApplicationContext.refresh

(AbstractApplicationContext.java:407)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>

(AnnotationConfigApplicationContext.java:65)
at com.mkyong.core.App.main(App.java:21)
Caused by: java.lang.NoClassDefFoundError: org/objectweb/asm/Type
at net.sf.cglib.core.TypeUtils.parseType(TypeUtils.java:180)
at net.sf.cglib.core.KeyFactory.<clinit>(KeyFactory.java:66)
at net.sf.cglib.proxy.Enhancer.<clinit>(Enhancer.java:69)
at org.springframework.context.annotation.ConfigurationClassEnhancer.newEnhancer

(ConfigurationClassEnhancer.java:101)
at org.springframework.context.annotation.ConfigurationClassEnhancer.enhance

(ConfigurationClassEnhancer.java:89)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses

(ConfigurationClassPostProcessor.java:238)
… 6 more
Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
… 12 more
这是因为项目中SpringMongoConfig文件中多了一个注解@Configuration,把它注释就可以。

错误三:
Exception in thread “main” org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception 

parsing XML document from class path resource [mongo-config.xml]; nested exception is 

java.lang.NoClassDefFoundError: org/springframework/dao/support/PersistenceExceptionTranslator
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions

(XmlBeanDefinitionReader.java:412)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions

(XmlBeanDefinitionReader.java:334)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions

(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions

(AbstractBeanDefinitionReader.java:143)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions

(AbstractBeanDefinitionReader.java:178)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions

(AbstractBeanDefinitionReader.java:149)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions

(AbstractBeanDefinitionReader.java:212)
at org.springframework.context.support.GenericXmlApplicationContext.load

(GenericXmlApplicationContext.java:105)
at org.springframework.context.support.GenericXmlApplicationContext.<init>

(GenericXmlApplicationContext.java:68)
at com.mkyong.core.App.main(App.java:24)
Caused by: java.lang.NoClassDefFoundError: org/springframework/dao/support/PersistenceExceptionTranslator
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.springframework.data.document.mongodb.config.MongoParser.getBeanClass(MongoParser.java:38)
at org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser.parseInternal

(AbstractSingleBeanDefinitionParser.java:66)
at org.springframework.beans.factory.xml.AbstractBeanDefinitionParser.parse

(AbstractBeanDefinitionParser.java:59)
at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:73)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement

(BeanDefinitionParserDelegate.java:1335)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement

(BeanDefinitionParserDelegate.java:1325)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions

(DefaultBeanDefinitionDocumentReader.java:135)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions

(DefaultBeanDefinitionDocumentReader.java:93)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions

(XmlBeanDefinitionReader.java:493)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions

(XmlBeanDefinitionReader.java:390)
… 9 more
Caused by: java.lang.ClassNotFoundException: org.springframework.dao.support.PersistenceExceptionTranslator
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
… 31 more
缺少包spring-tx-3.0.5.RELEASE.jar

错误四:
Exception in thread “main” org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 84 in XML 

document from class path resource [mongo-config.xml] is invalid; nested exception is org.xml.sax.SAXParseException; 

systemId: http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd; lineNumber: 84; columnNumber: 51; 

src-resolve: 无法将名称 ‘repository:repository’ 解析为 ‘type definition’ 组件。
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions

(XmlBeanDefinitionReader.java:396)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions

(XmlBeanDefinitionReader.java:334)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions

(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions

(AbstractBeanDefinitionReader.java:143)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions

(AbstractBeanDefinitionReader.java:178)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions

(AbstractBeanDefinitionReader.java:149)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions

(AbstractBeanDefinitionReader.java:212)
at org.springframework.context.support.GenericXmlApplicationContext.load

(GenericXmlApplicationContext.java:105)
at org.springframework.context.support.GenericXmlApplicationContext.<init>

(GenericXmlApplicationContext.java:68)
at com.mkyong.core.App.main(App.java:24)
Caused by: org.xml.sax.SAXParseException; systemId: http://www.springframework.org/schema/data/mongo/spring-mongo-

1.0.xsd; lineNumber: 84; columnNumber: 51; src-resolve: 无法将名称 ‘repository:repository’ 解析为 ‘type definition’ 

组件。
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.reportSchemaErr(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.reportSchemaError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.getGlobalDecl(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDComplexTypeTraverser.traverseComplexContent

(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDComplexTypeTraverser.traverseComplexTypeDecl

(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDComplexTypeTraverser.traverseGlobal(Unknown 

Source)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.traverseSchemas(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.parseSchema(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.loadSchema(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.findSchemaGrammar(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.emptyElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown 

Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:75)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions

(XmlBeanDefinitionReader.java:388)
… 9 more
缺少包spring-data-commons-core-1.0.0.RC1.jar

错误五:
Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name 

‘mongo’: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: 

Could not instantiate bean class [org.springframework.data.document.mongodb.MongoFactoryBean]: Constructor threw 

exception; nested exception is java.lang.NoClassDefFoundError: 

org/springframework/data/document/UncategorizedDocumentStoreException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean

(AbstractAutowireCapableBeanFactory.java:965)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance

(AbstractAutowireCapableBeanFactory.java:911)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean

(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean

(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton

(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons

(DefaultListableBeanFactory.java:563)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization

(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh

(AbstractApplicationContext.java:425)
at org.springframework.context.support.GenericXmlApplicationContext.<init>

(GenericXmlApplicationContext.java:69)
at com.mkyong.core.App.main(App.java:24)
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class 

[org.springframework.data.document.mongodb.MongoFactoryBean]: Constructor threw exception; nested exception is 

java.lang.NoClassDefFoundError: org/springframework/data/document/UncategorizedDocumentStoreException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:141)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate

(SimpleInstantiationStrategy.java:74)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean

(AbstractAutowireCapableBeanFactory.java:958)
… 12 more
Caused by: java.lang.NoClassDefFoundError: org/springframework/data/document/UncategorizedDocumentStoreException
at org.springframework.data.document.mongodb.MongoFactoryBean.<init>(MongoFactoryBean.java:54)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:126)
… 14 more
Caused by: java.lang.ClassNotFoundException: org.springframework.data.document.UncategorizedDocumentStoreException
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
… 20 more
缺少包spring-data-document-core-1.0.0.M2.jar

错误六:
Exception in thread “main” java.lang.NoClassDefFoundError: org/springframework/expression/PropertyAccessor
at org.springframework.context.support.AbstractApplicationContext.prepareBeanFactory

(AbstractApplicationContext.java:483)
at org.springframework.context.support.AbstractApplicationContext.refresh

(AbstractApplicationContext.java:400)
at org.springframework.context.support.GenericXmlApplicationContext.<init>

(GenericXmlApplicationContext.java:69)
at com.mkyong.core.App.main(App.java:24)
Caused by: java.lang.ClassNotFoundException: org.springframework.expression.PropertyAccessor
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
… 4 more
缺少包org.springframework.expression-3.0.5.RELEASE.jar

错误七:
Exception in thread “main” java.lang.NoClassDefFoundError: org/springframework/asm/ClassVisitor
at org.springframework.context.support.GenericApplicationContext.<init>(GenericApplicationContext.java:103)
at org.springframework.context.support.GenericXmlApplicationContext.<init>

(GenericXmlApplicationContext.java:67)
at com.mkyong.core.App.main(App.java:24)
Caused by: java.lang.ClassNotFoundException: org.springframework.asm.ClassVisitor
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
… 3 more
缺少包org.springframework.asm-3.0.5.RELEASE.jar

最后介绍几个下载包的地方:


 http://www.findjar.com/index.x

Maven-Focused Java Class and Archive Search Enginehttp://www.jarvana.com/jarvana/

Programming tutorials and source code examples http://www.java2s.com/

http://www.jar114.com/


Spring Data & MongoDB

In this article we are going to cover the following topics:

  1. MongoDB Installation on Windows Machine.
  2. MongoDB Java Example.
  3. Spring Data & MongoDB.

  MongoDB Installation on Windows Machine:

     Download MongoDB from official MongoDB website.

     Unzip MongoDB files to your prefer location, for example : “D:mongodb-win32-x86_64-1.8.3“.

     MongoDB won’t create data directory automatically. You need to create a data directory for MongoDB, for example : “D:mongodb-data“.

    mongod.exe is the database server daemon, run it and point it to the data directory, via “–dbpath” argument.

D:mongodb-win32-x86_64-1.8.3bin>mongod --dbpath "D:mymongodb-data" 

  In the output, you will notice that MongoDB started a web admin interface listening on port 28017.

   To access it, just type http://your-ipaddress:28017.

   In order to connect to your MongoDB server type D:mongodb-win32-x86_64-1.8.3bin>mongo

   If you are able to view the MongoDB web admin interface and also connected to the database server via mongo.exe, then your MongoDB is installed on the Windows successfully.

 

  MongoDB Java Example:

    A simple Java MongoDB example.

    Technologies and tools used:

  1. MongoDB 1.8.3
  2. MongoDB-Java-Driver 2.6.5
  3. JDK 1.6
package edu.seua.mongo;

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

/**
 * Java MongoDB Example
 * 
 */
public class MongoApp {

    public static void main(String[] args) {

	try {
	    // connect to mongoDB
	    Mongo mongo = new Mongo("localhost", 27017);

	    // if database doesn't exists, mongoDB will create it
	    DB db = mongo.getDB("mydb");

	    // Get collection from MongoDB, database named "mydb"
	    // if collection doesn't exists, mongoDB will create it
	    DBCollection collection = db.getCollection("myCollection");

	    // create a document to store attributes
	    BasicDBObject document = new BasicDBObject();
	    document.put("id", 100);
	    document.put("name", "simple name");
	    document.put("message", "simple message");
	    

	    // save it into collection named "myCollection"
	    collection.insert(document);

	    // search query
	    BasicDBObject searchQuery = new BasicDBObject();
	    searchQuery.put("id", 100);

	    DBCursor cursor = collection.find(searchQuery);

	    // loop over the cursor and display the result
	    while (cursor.hasNext()) {
		System.out.println(cursor.next());
	    }

	} catch (UnknownHostException e) {
	    e.printStackTrace();
	} catch (MongoException e) {
	    e.printStackTrace();
	}
    }
}

Output

{ 
   "_id" : { "$oid" : "4e5936ca602fbf0c50e0c9d0"} , 
   "id" : 100 , "name" : "simple name" , "message" : "simple message"
}

Now it’s time for Spring Data & MongoDB:

    Technologies and jars used:

  1. MongoDB 1.8.3
  2. JDK 1.6
  3. mongo-2.6.5.jar
  4. org.springframework.context-3.0.5.RELEASE.jar
  5. org.springframework.core-3.0.5.RELEASE.jar
  6. org.springframework.beans-3.0.5.RELEASE.jar
  7. commons-logging-1.1.1.jar
  8. org.springframework.asm-3.0.5.RELEASE.jar
  9. spring-data-mongodb-1.0.0.M2.jar
  10. slf4j-api-1.6.1.jar
  11. slf4j-jdk14-1.6.1.jar
  12. spring-dao-2.0.8.jar
  13. spring-expression-3.1.0.M2.jar
  14. spring-data-commons-core-1.1.0.M1.jar
  15. spring-tx-3.1.0.M1.jar
  16. spring-data-document-core-1.0.0.M2.jar



Spring XML configuration file (mongo-config.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/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">
 
	<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="myNewdb" />
		<constructor-arg name="defaultCollectionName" value="myNewCollection" />
	</bean>
 
	<!-- To translate any MongoExceptions thrown in @Repository annotated classes -->
	<context:annotation-config />
 
</beans>

  Let’s create Employee DTO

package edu.seua.mongo;

public class Employee {

    private String id;
    private String firstname;
    private String lastname;
    private int age;

    public Employee() {
    }

    public Employee(String id, String firstname, String lastname, int age) {
	super();
	this.id = id;
	this.firstname = firstname;
	this.lastname = lastname;
	this.age = age;
    }

    public String getId() {
	return id;
    }

    public void setId(String id) {
	this.id = id;
    }

    public String getFirstname() {
	return firstname;
    }

    public void setFirstname(String firstname) {
	this.firstname = firstname;
    }

    public String getLastname() {
	return lastname;
    }

    public void setLastname(String lastname) {
	this.lastname = lastname;
    }

    public int getAge() {
	return age;
    }

    public void setAge(int age) {
	this.age = age;
    }

    @Override
    public String toString() {
	return "Employee [age=" + age + ", firstname=" + firstname + ", id="
		+ id + ", lastname=" + lastname + "]";
    }

}

Full Example   

    Full example shows you how to use Spring data to perform CRUD operations in mongoD.

    The employee object is saved into a collection named employees.

package edu.seua.mongo;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
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;

/**
 * Java Spring Data & MongoDB Example
 * 
 */
public class SpringDataMongoApp {

    public static void main(String[] args) {

	ApplicationContext ctx = new ClassPathXmlApplicationContext("edu/seua/mongo/mongo-config.xml");

	MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");

	Employee employee = new Employee("100", "firstName", "lastName", 23);

	// save
	mongoOperation.save("employees", employee);

	// find
	Employee savedEmployee = mongoOperation.findOne("employees", new Query(Criteria.where(
		"id").is("100")), Employee.class);

	System.out.println("Saved Employee: " + savedEmployee);

	// update
	mongoOperation.updateFirst("employees", new Query(Criteria.where(
		"firstname").is("firstName")), Update.update("lastname",
		"new lastName"));

	// find
	Employee updatedEmployee = mongoOperation.findOne("employees", new Query(
		Criteria.where("id").is("100")), Employee.class);

	System.out.println("Updated Employee: " + updatedEmployee);

	// delete
	mongoOperation.remove("employees", new Query(Criteria.where("id").is(
		"100")), Employee.class);

	// List
	List<Employee> listEmployee = mongoOperation.getCollection("employees", Employee.class);
	System.out.println("size of employees = " + listEmployee.size());

    }
}

  Output

Saved Employee: Employee [age=23, firstname=firstName, id=100, lastname=lastName]
Updated Employee: Employee [age=23, firstname=firstName, id=100, lastname=new lastName]
size of employees = 0
Article Type: 
Opinion/Editorial

Mongodb快速入门之使用Java操作Mongodb

在本文中,将学习如何使用Java去编程实现对Mongodb的操作。

  HelloWorld程序

学习任何程序的第一步,都是编写HelloWorld程序,我们也不例外,看下如何通过Java编写一个HelloWorld的程序。

首先,要通过Java操作Mongodb,必须先下载Mongodb的Java驱动程序,可以在这里下载

新建立一个Java工程,将下载的驱动程序放在库文件路径下,程序代码如下:

package com.mkyong.core;
import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

/**
* Java + MongoDB Hello world Example
*
*/
public class App {
public static void main(String[] args) {
try {
//实例化Mongo对象,连接27017端口
Mongo mongo = new Mongo(“localhost”, 27017);
//连接名为yourdb的数据库,假如数据库不存在的话,mongodb会自动建立
DB db = mongo.getDB(“yourdb”);
// Get collection from MongoDB, database named “yourDB”
//从Mongodb中获得名为yourColleection的数据集合,如果该数据集合不存在,Mongodb会为其新建立
DBCollection collection = db.getCollection(“yourCollection”);
// 使用BasicDBObject对象创建一个mongodb的document,并给予赋值。
BasicDBObject document = new BasicDBObject();
document.put(“id”, 1001);
document.put(“msg”, “hello world mongoDB in Java”);
//将新建立的document保存到collection中去
collection.insert(document);
// 创建要查询的document
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put(“id”, 1001);
// 使用collection的find方法查找document
DBCursor cursor = collection.find(searchQuery);
//循环输出结果
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
System.out.println(“Done”);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}

最后,输出的结果为:

{ “_id” : { “$oid” : “4dbe5596dceace565d229dc3”} ,
“id” : 1001 , “msg” : “hello world mongoDB in Java”}
Done

在上面的例子中,演示了使用Java对Mongodb操作的重要方法和步骤,首先通过创建Mongodb对象,传入构造函数的参数是Mongodb的数据库所在地址和端口,然后使用

getDB方法获得要连接的数据库名,使用getCollection获得数据集合的名,然后通过新建立BasicDBObject对象去建立document,最后通过collection的insert方法,将建立的document保存到数据库中去。而collection的find方法,则是用来在数据库中查找document。

  从Mongodb中获得collection数据集

在Mongodb中,可以通过如下方法获得数据库中的collection:

  DBCollection collection = db.getCollection(“yourCollection”);

如果你不知道collection的名称,可以使用db.getCollectionNames()获得集合,然后再遍历,如下:

  DB db = mongo.getDB(“yourdb”);
Set collections = db.getCollectionNames();
for(String collectionName : collections){
System.out.println(collectionName);
}

完成的一个例子如下:

package com.mkyong.core;
import java.net.UnknownHostException;
import java.util.Set;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
/**
* Java : Get collection from MongoDB
*
*/
public class GetCollectionApp {
public static void main(String[] args) {
try {
Mongo mongo = new Mongo(“localhost”, 27017);
DB db = mongo.getDB(“yourdb”);
Set<String> collections = db.getCollectionNames();
for (String collectionName : collections) {
System.out.println(collectionName);
}
DBCollection collection = db.getCollection(“yourCollection”);
System.out.println(collection.toString());
System.out.println(“Done”);

} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}

  Mongodb中如何插入数据

下面,讲解下如何使用4种方式,将JSON数据插入到Mongodb中去。首先我们准备JSON

格式的数据,如下:

  {
“database” : “mkyongDB”,
“table” : “hosting”,
“detail” :
{
records : 99,
index : “vps_index1”,
active : “true”
}
}
}

我们希望用不同的方式,通过JAVA代码向Mongodb插入以上格式的JSON数据

第一种方法,是使用BasicDBObject,方法如下代码所示:

BasicDBObject document = new BasicDBObject();
document.put(“database”, “mkyongDB”);
document.put(“table”, “hosting”);
BasicDBObject documentDetail = new BasicDBObject();
documentDetail.put(“records”, “99”);
documentDetail.put(“index”, “vps_index1”);
documentDetail.put(“active”, “true”);
document.put(“detail”, documentDetail);
collection.insert(document);

第二种方法是使用BasicDBObjectBuilder对象,如下代码所示:

  BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
.add(“database”, “mkyongDB”)
.add(“table”, “hosting”);
BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
.add(“records”, “99”)
.add(“index”, “vps_index1”)
.add(“active”, “true”);
documentBuilder.add(“detail”, documentBuilderDetail.get());
collection.insert(documentBuilder.get());

第三种方法是使用Map对象,代码如下:

  Map documentMap =new HashMap();
documentMap.put(“database”, “mkyongDB”);
documentMap.put(“table”, “hosting”);
Map documentMapDetail =new HashMap();
documentMapDetail.put(“records”, “99”);
documentMapDetail.put(“index”, “vps_index1”);
documentMapDetail.put(“active”, “true”);
documentMap.put(“detail”, documentMapDetail);
collection.insert(new BasicDBObject(documentMap));

第四种方法,也就是最简单的,即直接插入JSON格式数据

  String json =”{‘database’ : ‘mkyongDB’,’table’ : ‘hosting’,”+
“‘detail’ : {‘records’ : 99, ‘index’ : ‘vps_index1’, ‘active’ : ‘true’}}}”;
DBObject dbObject =(DBObject)JSON.parse(json);
collection.insert(dbObject);

这里使用了JSON的parse方法,将解析后的JSON字符串转变为DBObject对象后再直接插入到collection中去。
完整的代码如下所示:

  packagecom.mkyong.core;
importjava.net.UnknownHostException;
importjava.util.HashMap;
importjava.util.Map;
importcom.mongodb.BasicDBObject;
importcom.mongodb.BasicDBObjectBuilder;
importcom.mongodb.DB;
importcom.mongodb.DBCollection;
importcom.mongodb.DBCursor;
importcom.mongodb.DBObject;
importcom.mongodb.Mongo;
importcom.mongodb.MongoException;
importcom.mongodb.util.JSON;
/**
* Java MongoDB : Insert a Document
*
*/
publicclass InsertDocumentApp {
publicstaticvoid main(String[] args){
try{
Mongo mongo =new Mongo(“localhost”, 27017);
DB db = mongo.getDB(“yourdb”);
// get a single collection
DBCollection collection = db.getCollection(“dummyColl”);
// BasicDBObject example
System.out.println(“BasicDBObject example…”);
BasicDBObject document =new BasicDBObject();
document.put(“database”, “mkyongDB”);
document.put(“table”, “hosting”);
BasicDBObject documentDetail =new BasicDBObject();
documentDetail.put(“records”, “99”);
documentDetail.put(“index”, “vps_index1”);
documentDetail.put(“active”, “true”);
document.put(“detail”, documentDetail);
collection.insert(document);
DBCursor cursorDoc = collection.find();
while(cursorDoc.hasNext()){
System.out.println(cursorDoc.next());
}
collection.remove(new BasicDBObject());
// BasicDBObjectBuilder example
System.out.println(“BasicDBObjectBuilder example…”);
BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
.add(“database”, “mkyongDB”)
.add(“table”, “hosting”);
BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
.add(“records”, “99”)
.add(“index”, “vps_index1”)
.add(“active”, “true”);
documentBuilder.add(“detail”, documentBuilderDetail.get());
collection.insert(documentBuilder.get());
DBCursor cursorDocBuilder = collection.find();
while(cursorDocBuilder.hasNext()){
System.out.println(cursorDocBuilder.next());
}
collection.remove(new BasicDBObject());
// Map example
System.out.println(“Map example…”);
Map documentMap =new HashMap();
documentMap.put(“database”, “mkyongDB”);
documentMap.put(“table”, “hosting”);
Map documentMapDetail =new HashMap();
documentMapDetail.put(“records”, “99”);
documentMapDetail.put(“index”, “vps_index1”);
documentMapDetail.put(“active”, “true”);
documentMap.put(“detail”, documentMapDetail);
collection.insert(new BasicDBObject(documentMap));
DBCursor cursorDocMap = collection.find();
while(cursorDocMap.hasNext()){
System.out.println(cursorDocMap.next());
}
collection.remove(new BasicDBObject());
// JSON parse example
System.out.println(“JSON parse example…”);
String json =”{‘database’ : ‘mkyongDB’,’table’ : ‘hosting’,”+
“‘detail’ : {‘records’ : 99, ‘index’ : ‘vps_index1’, ‘active’ : ‘true’}}}”;
DBObject dbObject =(DBObject)JSON.parse(json);
collection.insert(dbObject);
DBCursor cursorDocJSON = collection.find();
while(cursorDocJSON.hasNext()){
System.out.println(cursorDocJSON.next());
}
collection.remove(new BasicDBObject());
}catch(UnknownHostException e){
e.printStackTrace();
}catch(MongoException e){
e.printStackTrace();
}
}
}

  更新Document

假设如下的JSON格式的数据已经保存到Mongodb中去了,现在要更新相关的数据。

  {“_id” : {“$oid” : “x”} , “hosting” : “hostA” , “type” : “vps” , “clients” : 1000}
{“_id” : {“$oid” : “x”} , “hosting” : “hostB” , “type” : “dedicated server” , “clients” : 100}
{“_id” : {“$oid” : “x”} , “hosting” : “hostC” , “type” : “vps” , “clients” : 900}

假设现在要将hosting中值为hostB的进行更新,则可以使用如下的方法:

  BasicDBObject newDocument =new BasicDBObject();
newDocument.put(“hosting”, “hostB”);
newDocument.put(“type”, “shared host”);
newDocument.put(“clients”, 111);
collection.update(new BasicDBObject().append(“hosting”, “hostB”), newDocument);

可以看到,这里依然使用了BasicDBObject对象,并为其赋值了新的值后,然后使用collection的update方法,即可更新该对象。

更新后的输出如下:

  {“_id” : {“$oid” : “x”} , “hosting” : “hostA” , “type” : “vps” , “clients” : 1000}
{“_id” : {“$oid” : “x”} , “hosting” : “hostB” , “type” : “shared host” , “clients” : 111}
{“_id” : {“$oid” : “x”} , “hosting” : “hostC” , “type” : “vps” , “clients” : 900}

另外,还可以使用mongodb中的$inc修饰符号去对某个值进行更新,比如,要将hosting值为hostB的document的clients的值得更新为199(即100+99=199),可以这样:

  BasicDBObject newDocument =new BasicDBObject().append(“$inc”,
new BasicDBObject().append(“clients”, 99));
collection.update(new BasicDBObject().append(“hosting”, “hostB”), newDocument);

则输出如下:

  {“_id” : {“$oid” : “x”} , “hosting” : “hostA” , “type” : “vps” , “clients” : 1000}
{“_id” : {“$oid” : “x”} , “hosting” : “hostB” , “type” : “dedicated server” , “clients” : 199}
{“_id” : {“$oid” : “x”} , “hosting” : “hostC” , “type” : “vps” , “clients” : 900}

接下来,讲解$set修饰符的使用。比如要把hosting中值为hostA的document中的

type的值进行修改,则可以如下实现:

  BasicDBObject newDocument3 =new BasicDBObject().append(“$set”,
new BasicDBObject().append(“type”, “dedicated server”));
collection.update(new BasicDBObject().append(“hosting”, “hostA”), newDocument3);

则输出如下,把type的值从vps改为dedicated server:

  {“_id” : {“$oid” : “x”} , “hosting” : “hostB” , “type” : “dedicated server” , “clients” : 100}
{“_id” : {“$oid” : “x”} , “hosting” : “hostC” , “type” : “vps” , “clients” : 900}
{“_id” : {“$oid” : “x”} , “hosting” : “hostA” , “clients” : 1000 , “type” : “dedicated server”}

要注意的是,如果不使用$set的修饰符,而只是如下代码:

  BasicDBObject newDocument3 =new BasicDBObject().append(“type”, “dedicated server”);
collection.update(new BasicDBObject().append(“hosting”, “hostA”), newDocument3);

则会将所有的三个document的type类型都改为dedicated server了,因此要使用$set以更新特定的document的特定的值。

如果要更新多个document中相同的值,可以使用$multi,比如,要把所有vps为type的document,将它们的clients的值更新为888,可以如下实现:

  BasicDBObject updateQuery =new BasicDBObject().append(“$set”,
new BasicDBObject().append(“clients”, “888”));
collection.update(new BasicDBObject().append(“type”, “vps”), updateQuery, false, true);

输出如下:

  {“_id” : {“$oid” : “x”} , “hosting” : “hostA” , “clients” : “888” , “type” : “vps”}
{“_id” : {“$oid” : “x”} , “hosting” : “hostB” , “type” : “dedicated server” , “clients” : 100}
{“_id” : {“$oid” : “x”} , “hosting” : “hostC” , “clients” : “888” , “type” : “vps”}

最后,还是给出更新document的完整例子:

  package com.liao;
import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
publicclass UpdateDocumentApp {
publicstaticvoid printAllDocuments(DBCollection collection){
DBCursor cursor = collection.find();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
publicstaticvoid removeAllDocuments(DBCollection collection){
collection.remove(new BasicDBObject());
}
publicstaticvoid insertDummyDocuments(DBCollection collection){
BasicDBObject document = new BasicDBObject();
document.put(“hosting”, “hostA”);
document.put(“type”, “vps”);
document.put(“clients”, 1000);
BasicDBObject document2 = new BasicDBObject();
document2.put(“hosting”, “hostB”);
document2.put(“type”, “dedicated server”);
document2.put(“clients”, 100);
BasicDBObject document3 = new BasicDBObject();
document3.put(“hosting”, “hostC”);
document3.put(“type”, “vps”);
document3.put(“clients”, 900);
collection.insert(document);
collection.insert(document2);
collection.insert(document3);
}
publicstaticvoid main(String[] args) {
try {
Mongo mongo = new Mongo(“localhost”, 27017);
DB db = mongo.getDB(“yourdb”);
DBCollection collection = db.getCollection(“dummyColl”);
System.out.println(“Testing 1…”);
insertDummyDocuments(collection);
//find hosting = hostB, and update it with new document
BasicDBObject newDocument = new BasicDBObject();
newDocument.put(“hosting”, “hostB”);
newDocument.put(“type”, “shared host”);
newDocument.put(“clients”, 111);
collection.update(new BasicDBObject().append(“hosting”, “hostB”), newDocument);
printAllDocuments(collection);
removeAllDocuments(collection);
System.out.println(“Testing 2…”);
insertDummyDocuments(collection);
BasicDBObject newDocument2 = new BasicDBObject().append(“$inc”,
new BasicDBObject().append(“clients”, 99));
collection.update(new BasicDBObject().append(“hosting”, “hostB”), newDocument2);
printAllDocuments(collection);
removeAllDocuments(collection);
System.out.println(“Testing 3…”);
insertDummyDocuments(collection);
BasicDBObject newDocument3 = new BasicDBObject().append(“$set”,
new BasicDBObject().append(“type”, “dedicated server”));
collection.update(new BasicDBObject().append(“hosting”, “hostA”), newDocument3);
printAllDocuments(collection);
removeAllDocuments(collection);
System.out.println(“Testing 4…”);
insertDummyDocuments(collection);
BasicDBObject updateQuery = new BasicDBObject().append(“$set”,
new BasicDBObject().append(“clients”, “888”));
collection.update(
new BasicDBObject().append(“type”, “vps”), updateQuery, false, true);
printAllDocuments(collection);
removeAllDocuments(collection);
System.out.println(“Done”);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}

  查询Document

下面学习如何查询document,先用下面的代码往数据库中插入1-10数字:

  for(int i=1; i <=10; i++){
collection.insert(new BasicDBObject().append(“number”, i));

}

接下来,看下如下的例子:

  1) 获得数据库中的第一个document:

  DBObject doc = collection.findOne();
System.out.println(dbObject);

输出为:

  {“_id” : {“$oid” : “4dc7f7b7bd0fb9a86c6c80bd”} , “number” : 1}

  2)获得document的集合

  DBCursor cursor = collection.find();
while(cursor.hasNext()){
System.out.println(cursor.next());
}

这里,使用collection.find()方法,获得当前数据库中所有的documents对象集合

然后通过对DBCursor对象集合的遍历,即可输出当前所有documents。输出如下:

  {“_id” : {“$oid” : “4dc7f7b7bd0fb9a86c6c80bd”} , “number” : 1}
//……….中间部分省略,为2到9的输出
{“_id” : {“$oid” : “4dc7f7b7bd0fb9a86c6c80c6”} , “number” : 10}

  3) 获取指定的document

比如要获得number=5的document对象内容,可以使用collection的find方法即可,如下:

  BasicDBObject query =new BasicDBObject();
query.put(“number”, 5);
DBCursor cursor = collection.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}

即输出:

  {“_id” : {“$oid” : “4dc7f7b7bd0fb9a86c6c80c1”} , “number” : 5}

  4) 使用in操作符号

在mongodb中,也可以使用in操作符,比如要获得number=9和number=10的document对象,可以如下操作:

  BasicDBObject query =new BasicDBObject();
List list =new ArrayList();
list.add(9);
list.add(10);
query.put(“number”, new BasicDBObject(“$in”, list));
DBCursor cursor = collection.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}

这里使用了一个List,并将list传入到BasicDBObject的构造函数中,并使用了in操作符号,输出如下:

  {“_id” : {“$oid” : “4dc7f7b7bd0fb9a86c6c80c5”} , “number” : 9}
{“_id” : {“$oid” : “4dc7f7b7bd0fb9a86c6c80c6”} , “number” : 10}

  5) 使用>,<等比较符号

在mongodb中,也可以使用比如>,<等数量比较符号,比如要输出number>5的document集合,则使用“$gt”即可,同理,小于关系则使用$lt,例子如下:

  BasicDBObject query =new BasicDBObject();
query.put(“number”, new BasicDBObject(“$gt”, 5));
DBCursor cursor = collection.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}

输出如下:

  {“_id” : {“$oid” : “4dc7f7b7bd0fb9a86c6c80c2”} , “number” : 6}
{“_id” : {“$oid” : “4dc7f7b7bd0fb9a86c6c80c3”} , “number” : 7}
{“_id” : {“$oid” : “4dc7f7b7bd0fb9a86c6c80c4”} , “number” : 8}
{“_id” : {“$oid” : “4dc7f7b7bd0fb9a86c6c80c5”} , “number” : 9}
{“_id” : {“$oid” : “4dc7f7b7bd0fb9a86c6c80c6”} , “number” : 10}
也可以多个比较符号一起使用,比如要输出number>5和number<8的document,则如下:
BasicDBObject query =new BasicDBObject();
query.put(“number”, new BasicDBObject(“$gt”, 5).append(“$lt”, 8));
DBCursor cursor = collection.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}

同样,如果是不等于的关系的话,可以使用$ne操作符,如下:

  BasicDBObject query5 =new BasicDBObject();
query5.put(“number”, new BasicDBObject(“$ne”, 8));
DBCursor cursor6 = collection.find(query5);
while(cursor6.hasNext()){
System.out.println(cursor6.next());
}

以上输出number=8之外的所有document。

  删除document

下面我们学习如何删除document,依然以上面的已插入的1-10的documents集合为例说明:

  1) 删除第一个document

  DBObject doc = collection.findOne();
collection.remove(doc);

  2) 删除指定的document

比如删除number=2的document,如下方法:

  BasicDBObject document =new BasicDBObject();
document.put(“number”, 2);
collection.remove(document);

要注意的是,如下的方法将只会删除number=3的document。

  BasicDBObject document =new BasicDBObject();
document.put(“number”, 2);
document.put(“number”, 3);
collection.remove(document);

  3) 使用in 操作符号指定删除document

下面的例子将同时删除number=4和number=5的document,使用的是in操作符

  BasicDBObject query2 =new BasicDBObject();
List list =new ArrayList();
list.add(4);
list.add(5);
query2.put(“number”, new BasicDBObject(“$in”, list));
collection.remove(query2);

  4) 使用“$gt”删除大于某个值的document

  BasicDBObject query =new BasicDBObject();
query.put(“number”, new BasicDBObject(“$gt”, 9));
collection.remove(query);

以上会删除number=10的document。

  5) 删除所有的document

  DBCursor cursor = collection.find();
while(cursor.hasNext()){
collection.remove(cursor.next());
}

  保存图片到Mongodb

下面将讲解如何使用Java MongoDB GridFS API去保存图片等二进制文件到Monodb,关于Java MongoDB GridFS API的详细论述,请参考http://www.mongodb.org/display/DOCS/GridFS+Specification

  1)保存图片

代码段如下:

  String newFileName =”mkyong-java-image”;
File imageFile =newFile(“c:\JavaWebHosting.png”);
GridFS gfsPhoto =new GridFS(db, “photo”);
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
gfsFile.setFilename(newFileName);
gfsFile.save();

这里,将c盘下的JavaWebHosting.png保存到mongodb中去,并命名为mkyong-java-image。

  2) 读取图片信息

代码段如下

  String newFileName =”mkyong-java-image”;
GridFS gfsPhoto =new GridFS(db, “photo”);
GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
System.out.println(imageForOutput);

将会输出JSON格式的结果;

  {
“_id” :
{
“$oid” : “4dc9511a14a7d017fee35746”
} ,
“chunkSize” : 262144 ,
“length” : 22672 ,
“md5” : “1462a6cfa27669af1d8d21c2d7dd1f8b” ,
“filename” : “mkyong-java-image” ,
“contentType” : null ,
“uploadDate” :
{
“$date” : “2011-05-10T14:52:10Z”
} ,
“aliases” : null
}

可以看到,输出的是文件的属性相关信息。
  3) 输出已保存的所有图片

下面代码段,输出所有保存在photo命名空间下的图片信息:

  GridFS gfsPhoto =new GridFS(db, “photo”);
DBCursor cursor = gfsPhoto.getFileList();
while(cursor.hasNext()){
System.out.println(cursor.next());
}

  4) 从数据库中读取一张图片并另存

下面的代码段,从数据库中读取一张图片并另存为另外一张图片到磁盘中

  String newFileName =”mkyong-java-image”;
GridFS gfsPhoto =new GridFS(db, “photo”);
GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
imageForOutput.writeTo(“c:\JavaWebHostingNew.png”);

  5) 删除图片

  String newFileName =”mkyong-java-image”;
GridFS gfsPhoto =new GridFS(db, “photo”);
gfsPhoto.remove(gfsPhoto.findOne(newFileName));

  如何将JSON数据格式转化为DBObject格式

在mongodb中,可以使用com.mongodb.util.JSON类,将JSON格式的字符串转变为DBObject对象。MongoDB for JAVA驱动中提供了用于向数据库中存储普通对象的接口DBObject,当一个文档从MongoDB中取出时,它会自动把文档转换成DBObject接口类型,要将它实例化为需要的对象。比如:

  {
‘name’ : ‘mkyong’,
‘age’ : 30
}

这样的JSON格式字符串,转换方法为:

  DBObject dbObject =(DBObject) JSON.parse(“{‘name’:’mkyong’, ‘age’:30}”);

完整的代码如下:

  packagecom.mkyong.core;
importjava.net.UnknownHostException;
importcom.mongodb.DB;
importcom.mongodb.DBCollection;
importcom.mongodb.DBCursor;
importcom.mongodb.DBObject;
importcom.mongodb.Mongo;
importcom.mongodb.MongoException;
importcom.mongodb.util.JSON;
/**
* Java MongoDB : Convert JSON data to DBObject
*
*/
publicclass App {
publicstaticvoid main(String[] args){
try{
Mongo mongo =new Mongo(“localhost”, 27017);
DB db = mongo.getDB(“yourdb”);
DBCollection collection = db.getCollection(“dummyColl”);
DBObject dbObject =(DBObject) JSON
.parse(“{‘name’:’mkyong’, ‘age’:30}”);
collection.insert(dbObject);
DBCursor cursorDoc = collection.find();
while(cursorDoc.hasNext()){
System.out.println(cursorDoc.next());
}
System.out.println(“Done”);
}catch(UnknownHostException e){
e.printStackTrace();
}catch(MongoException e){
e.printStackTrace();
}
}
}

则输出为:

  {“_id” : {“$oid” : “4dc9ebb5237f275c2fe4959f”} , “name” : “mkyong” , “age” : 30}
  Done

可以看到,将JSON格式的数据类型直接转换为mongodb中的文档类型并输出。

  小结:

本文学习了如何使用Mongodb for JAVA驱动,对mongodb进行日常的数据库操作,比如增加,删除和修改,下一篇教程中,将指导学习Spring对mongodb的操作。