先感谢同事梁员外<MongoDB with Morphia>的技术分享,下面是一些相关的笔记,当然啦,在应用Morphia之前需要有MongoDB的使用经验.
What is Morphia?
Morphia is a lightweight type-safe library for mapping your Java objects to/from MongoDB
简单的来说Morphia与MongoDB的关系就如Hibernate与关系数据库的关系, 是一个实现Java对象到MongoDB双向映射的类库。
下面是摘自Morphia官方的简介,带有一定的广告性,呵呵
Easy to use, and very lightweight; reflection is used once per type and cached.
Annotations describe mapping behavior; there are no XML files.
Provides Datastore and DAO<T,V> data access abstractions, or roll your own...
Type-safe Query support
Works with Guice, Spring, and other DI frameworks.
Has many extension points to build on
Does not store Null/Empty values (by default).
GWT support (entities are just POJOs) --(GWT ignores annotations)
Advanced mapper that allows raw conversion, void toObject(DBObject) or DBObject fromObject(Object)
下载 morphia.jar
将jar导入到工程后,看看mongodb和morphia的初始化
初始化Mongo(MongoDB Java Api)

初始化Morphia
在mapPackage需要制定一系列的pojo类
对POJO类进行存储操作


以上代码创建了两个领域Hotel,Address,前者为实体存在,有自己的生命周期,后者则为内嵌在实体之中,没有独立的生命周期, 关于这些注解的详细含义,以及Morphia提供的其他注解,请参见其官方文档。
以下说说Morphia与Spring的结合

com.***.cvus.dao.MorphiaBean 是自己封装的一个SpringBean类
public class MorphiaBean extends Morphia {
…
private Mongo mongo = null;
private String dbName = null;
public Datastore getDataStore() {
if (this.mongo == null || this.dbName == null) {
return null;
}
return createDatastore(mongo, dbName);
}
…
}
MorphiaBean的应用
DataStrore—查询语法
直接ID查询:
简单条件查询:

DataStrore—保存\删除 语法
保存
删除
Query—复杂查询
Filter方法:

获取第一个数据
获取列表:
Query—排序,分页
排序

分页
UpdateOperaions—更新操作
执行语句
updateQuery:查询条件(Class:Query)
ops:更新操作(Class:UpdateOperations)
ops( UpdateOperations )参数的语法:
http://code.google.com/docreader/#p=morphia&s=morphia&t=Updating
@Embedded & @Reference
http://code.google.com/docreader/#p=morphia&s=morphia&t=EmbeddedAnnotation
http://code.google.com/docreader/#p=morphia&s=morphia&t=ReferenceAnnotation
----------------------------------------
by 陈于喆
QQ:34174409
Mail: chenyz@corp.netease.com