---
title: "MongoDB ODM 框架MongoMongo-简化你的数据存储"
author: "allwefantasy"
date: "2013-03-06T07:37:55Z"
tags: []
categories: ["开源软件"]
slug: "mongodb-odm-mongomongo"
draft: false
lastmod: "2013-03-07T17:01:17Z"
id: 1823028
url: "https://allwefantasy.iteye.com/blog/1823028"
---

[MongMongo](https://github.com/allwefantasy/mongomongo)是一个用Java写的ODM框架，使得对MongoDB的操作更加便捷。

 

MongoMongo努力为Java开发者提供类似于[ActiveORM](https://github.com/allwefantasy/active_orm) 或者 Hibernate的操作API,并且保留了MongoDB的schemaless，document-based 设计,动态查询,原子修改操作等特性。当然你可以很方便的绕开MongoMongo而使用Java Driver 原生提供的功能。

 

下面是一段示例代码:

 

 

```
public class Blog extends Document {
    static {
        storeIn("blogs");                
        hasManyEmbedded("articles", new Options(map(
                Options.n_kclass, Article.class
        )));
        //create index
        index(map("blogTitle", -1), map(unique,true));
        //validate uerName field
        validate("userName",map(length,map(
                minimum,5
        )));

    }
    //association related
    public AssociationEmbedded articles() {throw new AutoGeneration();}
    private String userName;
    private String blogTitle;
}

public class Article extends Document {
    static {        
        belongsToEmbedded("blog", new Options(map(
                Options.n_kclass, Blog.class
        )));
    }
    public AssociationEmbedded blog() {throw new AutoGeneration();}
    private String title;
    private String body;
}

public class Usage{
  public static void main(String[] args){

     Blog blog = Blog.where(map("userName","sexy java")).in(map("id",list(1,2,3))).singleFetch();
     blog.articles().build(map("title","i am title","body","i am body"));
     blog.save();
  }

}
```

 

 我们可以看到这是一个典型的充血模型。关联，存储，创建索引，设置别名等操作都简单的在static 块中调用一个函数即可实现。如果你用一些动态语言，你会发现这种方法级声明语法是非常流行，写起来也非常舒服。

 

其实对于MongoDB相关的框架已经有很多，那么MongoMongo的优势何在？我们简单做个代码对比就一目了然了。

 

以 SpringData for MongoDB为例,典型的操作如下：

 

```
 public static void main( String[] args )
    {
        MongoOperations mongoOps = new MongoTemplate(new Mongo(), "mydb");
        Person person = new Person();
        person.setName("Joe");
        person.setAge(10);
        mongoOps.insert(person);
        log.info(mongoOps.findOne(new Query(Criteria.where("name").is("Joe")), Person.class));
    }
```

 

 

 

事实上大部分Java ODM都是如此操作Model的。为了构造查询串引入Criteria对象，为了进行查询引入Query对象,查询时还要申明Person对象等。

此外对于索引，别名，校验等设置也较为繁琐和不清晰，通常将将这些信息放在字段的Annotation上，或者设置一些Configuration对象等。

而MongoMongo将大部分对collection的配置都放在Model的代码块中，清晰明了，且便于管理。

 

相应的MongoMongo代码

 

```
public static void main( String[] args )
 {
     Person person =  Person.create(map("name","Joe","age",34));
     person.save();
     log.info(Person.where(map("name","Joe")).singleFetch()); 
 }
```

 

 

 

MongoMongo的查询也是典型的ORM的操作方式。

 

```
Blog blog = Blog.where(map("active",true)).in(map("id",list(1,2,3))).singleFetch();
```

 

通常你还可以写成:

```
public class Blog extends Document {
   public Criteria active(){
    return where(map("active",true));
   } 
}
```

 

之后你就可以这样调用:

```
List<Blog> blogs = Blog.active().where(map("userName","jack")).fetch();
```

 

复用性是很高的。

如果你使用过 [ActiveORM](https://github.com/allwefantasy/active_orm),那么这样操作MongoDB 你会感觉很顺手。

MongoMongo目前在一些内部小项目中使用。根据需求定制的，所以相对来说没有 [ActiveORM](https://github.com/allwefantasy/active_orm) 完善，很多细节和功能没有考虑到，但是都可以通过其暴露的MongoDB Driver 解决。

 

举个例子:

 

```
TTUser.collection().find(new BasicDBObject("tagName","cool"));
```

 

这个时候你尅通过collection()方法获得DBCollection对象。

 

当然也希望以后能遇到一个复杂的项目，从而能在该项目中完善MongoMongo.

如果你将它用在自己的项目中，我想肯定能节约相当多的代码。

 

大家不妨根据 [5 steps to run a application on MongoMongo](/blog/1822511)  体验下。