随笔-57  评论-117  文章-1  trackbacks-0
 

上两篇文章:http://www.cnblogs.com/hoojo/archive/2011/06/01/2066426.html

http://www.cnblogs.com/hoojo/archive/2011/06/02/2068665.html

介绍到了在MongoDB的控制台完成MongoDB的数据操作、以及通过Java MongoDB 的驱动完成在Java中对MongoDB的操作,通过前两篇文章我们对MongoDB有了全面、深刻的认识和理解。现在我们就看看利用Morphia库来操作MongoDB。

开发环境:

System:Windows

IDE:eclipse、MyEclipse 8

Database:mongoDB

开发依赖库:

JavaEE5、mongo-2.5.3.jar、junit-4.8.2.jar, morphia-0.99.jar

Email:hoojo_@126.com

Blog:http://blog.csdn.net/IBM_hoojo

http://hoojo.cnblogs.com/

一、准备工作

1、 首先,下载mongoDB对Java支持的驱动包

驱动包下载地址:https://github.com/mongodb/mongo-java-driver/downloads

mongoDB对Java的相关支持、技术:http://www.mongodb.org/display/DOCS/Java+Language+Center

驱动源码下载:https://download.github.com/mongodb-mongo-java-driver-r2.6.1-7-g6037357.zip

在线查看源码:https://github.com/mongodb/mongo-java-driver

Morphia jar包下载:http://code.google.com/p/morphia/downloads/list

2、 下面建立一个JavaProject工程,导入下载下来的驱动包。即可在Java中使用Morphia,目录如下:

clip_image002

二、Java操作MongoDB示例

在本示例之前你需要启动mongod.exe的服务,在你安装mongoDB的目录中,找到mongod.exe启动服务后,下面的程序才能顺利执行;

1、 Java操作mongoDB数据库,操作索引

Mongo mongo = new Mongo();

这样就创建了一个MongoDB的数据库连接对象,它默认连接到当前机器的localhost地址,端口是27017。

DB db = mongo.getDB(“test”);

这样就获得了一个test的数据库,如果mongoDB中没有创建这个数据库也是可以正常运行的。如果你读过上一篇文章就知道,mongoDB可以在没有创建这个数据库的情况下,完成数据的添加操作。当添加的时候,没有这个库,mongoDB会自动创建当前数据库。

得到了db,下一步我们要获取一个“聚集集合DBCollection”,通过db对象的getCollection方法来完成。

DBCollection users = db.getCollection("users");

这样就获得了一个DBCollection,它相当于我们数据库的“表”。

查询所有数据

DBCursor cur = users.find();

while (cur.hasNext()) {

System.out.println(cur.next());

}

用BasicDBObjectBuilder,向users对象中添加数据

user = BasicDBObjectBuilder.start("id", 1546555)

.append("name", "jojo").add("address", "gz")

.append("email", "hoojo_@126.com")

.get();

插入数据

users.insert(user);

可以利用JSON工具来序列化对象数据

JSON.serialize(cur)

完整源码

package com.hoo.test;
 
import java.net.UnknownHostException;
import com.hoo.entity.User;
import com.hoo.util.BasicDBObjectUtils;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;
 
/**
 * <b>function:</b> Mongo实例对象的相关方法测试
 * @author hoojo
 * @createDate 2011-5-24 下午02:42:29
 * @file MongoDBTest.java
 * @package com.hoo.test
 * @project MongoDB
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public class MongoDBTest {
 
    public static void main(String[] args) throws UnknownHostException, MongoException {
        Mongo mg = new Mongo();
        
        System.out.println("查询所有的Database的名称");
        for (String name : mg.getDatabaseNames()) {
            System.out.println("dbName: " + name);
        }
        
        System.out.println("查询test库中的所有collection集合(表)名称");
        DB db = mg.getDB("test");
        for (String name : db.getCollectionNames()) {
            System.out.println("collectionName: " + name);
        }
        
        System.out.println("添加测试数据");
        DBCollection users = db.getCollection("users");
        try {
            // 用自定义BasicDBObjectUtils工具类,将User Enity对象转换成DBObject
            DBObject user = BasicDBObjectUtils.castModel2DBObject(new User("345567", "jack", 22, "beijin"));
            users.insert(user);
            // 用BasicDBObjectBuilder构建一个DBObject对象
            user = BasicDBObjectBuilder.start("id", 1546555).append("name", "jojo").add("address", "gz").append("email", "hoojo_@126.com").get();
            users.insert(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        System.out.println("游标查询所有users集合数据");
        DBCursor cur = users.find();
        while (cur.hasNext()) {
            System.out.println(cur.next());
        }
        System.out.println("查询游标相关内容");
        System.out.println(cur.count());
        System.out.println(cur.getCursorId());
        System.out.println(cur.getOptions());
        System.out.println(cur.getQuery());
        System.out.println(cur.getSizes().listIterator());
        
        System.out.println(cur.itcount());
        //System.out.println(cur.length());
        System.out.println(cur.size());
        System.out.println(cur.numGetMores());
        System.out.println(cur.curr());
        //System.out.println(cur.toArray().get(0));
        
        System.out.println("显示游标查询到的所有内容: " + JSON.serialize(cur));
    }
}

工具类,将带有getter、setter方法的Java类序列化成DBObject对象

package com.hoo.util;
 
import java.lang.reflect.Method;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
 
/**
 * <b>function:</b> 将Entity/Model转换成DBObject
 * @author hoojo
 * @createDate 2011-5-30下午01:53:08
 * @file BasicDBObjectUtil.java
 * @package com.hoo.util
 * @project MongoDB
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
publicclass BasicDBObjectUtils {
    public static<T> DBObject castModel2DBObject(T entity) throws Exception {
        Method[] method =  entity.getClass().getMethods();
        
        DBObject dbObject = new BasicDBObject();
        for (Method m : method) {
            //System.out.println(m.getName());
            if (m.getName().startsWith("get")) {
                String name = m.getName().replace("get", "");
                for (Method m2 : method) {
                    if (m2.getName().equals("set" + name)) {
                        name = name.substring(0, 1).toLowerCase() + name.substring(1);
                        Object returnVal = m.invoke(entity, new Object[] {});
                        if (returnVal != null) {
                            //System.out.println(name + " : " + m.invoke(shipping, new Object[] {}));
                            dbObject.put(name, returnVal);
                        }
                    }
                }
            }
        }
        System.out.println("dbObject: " + dbObject);
        return dbObject;
    }
}

2、 完成索引操作,首先建立一个MongoDB4IndexTest.java,基本测试代码如下:

package com.hoo.test;
 
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.bson.types.ObjectId;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.mongodb.BasicDBObject;
import com.mongodb.Bytes;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.QueryOperators;
import com.mongodb.util.JSON;
 
/**
 * <b>function:</b> 实现MongoDB的Index操作
 * @author hoojo
 * @createDate 2011-6-2 下午03:21:23
 * @file MongoDB4IndexTest.java
 * @package com.hoo.test
 * @project MongoDB
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public class MongoDB4IndexTest {
    
    private Mongo mg = null;
    private DB db;
    private DBCollection users;
    
    @Before
    public void init() {
        try {
            mg = new Mongo();
            //mg = new Mongo("localhost", 27017);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (MongoException e) {
            e.printStackTrace();
        }
        //获取temp DB;如果默认没有创建,mongodb会自动创建
        db = mg.getDB("temp");
        //获取users DBCollection;如果默认没有创建,mongodb会自动创建
        users = db.getCollection("users");
    }
    
    @After
    public void destory() {
        if (mg != null)
            mg.close();
        mg = null;
        db = null;
        users = null;
        System.gc();
    }
    
    public void print(Object o) {
        System.out.println(o);
    }
}

3、 下面完成对象Collection的index的操作

/**
 * <b>function:</b> 测试Collection的index相关操作
 * @author hoojo
 * @createDate 2012-2-16 下午08:32:26
 */
@Test
public void testIndex() {
    query();
    
    for (DBObject index : coll.getIndexInfo()) {
        print("IndexInfo: " + index);
    }
    
    coll.dropIndexes();
    //创建索引
    coll.createIndex(new BasicDBObject("name", "idx_name"));
    print(coll.findOne(new BasicDBObject("name", "haha")));
    coll.createIndex(coll.findOne(new BasicDBObject("name", "haha")));
    DBObject o = new BasicDBObject("unique", true);
    //coll.createIndex(coll.findOne(), o);
    
    // 修改索引,如果存在就修改不存在就添加
    coll.ensureIndex(o);
    coll.ensureIndex("age_1");
    coll.ensureIndex(new BasicDBObject("age3_1", 6), new BasicDBObject("ts", -1));
    coll.ensureIndex(new BasicDBObject("age_2", 1), new BasicDBObject( "ts" , 1 ));
    coll.ensureIndex(new BasicDBObject("password", 2), new BasicDBObject( "z" , "idx" ));
    coll.ensureIndex(new BasicDBObject("password", 1), new BasicDBObject( "etc" , "idx" ));
    // 创建唯一索引
    coll.ensureIndex(new BasicDBObject("emial", 2), new BasicDBObject("unique", false));
    // 创建索引,指定索引名称default_index
    coll.ensureIndex(new BasicDBObject("address", 1), new BasicDBObject( "name" , "default_index"));
    // 创建索引对象,索引名称user_index
    coll.ensureIndex(coll.findOne(new BasicDBObject("name", "hoho")), "user_index");
    // 唯一索引
    coll.ensureIndex(coll.findOne(new BasicDBObject("name", "hehe")), "users_index_unique", true);
    
    // 查询所有索引
    for (DBObject index : coll.getIndexInfo()) {
        print("IndexInfo: " + index);
    }
    
    print(DBCollection.genIndexName(coll.findOne()));
    
    //coll.dropIndex(coll.findOne());
    print(DBCollection.genIndexName(new BasicDBObject("password", 2)));
    //coll.dropIndex(DBCollection.genIndexName(new BasicDBObject("password", 2)));
    //coll.dropIndexes();
    //coll.dropIndexes("assword_1");
}

三、Morphia基本操作

1、 morphia可以利用annotation对JavaEntity进行注解,那样我们就可以用morphia操作JavaEntity对象

package com.hoo.entity;
 
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
 
/**
 * <b>function:</b> JavaEntity对象
 * @author hoojo
 * @createDate 2011-5-31上午11:45:21
 * @file User.java
 * @package com.hoo.entity
 * @project Morphia
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
//利用morphia的annotation进行注解
@Entity
public class User {
    @Id
    private long id;
    
    private String name;
    private boolean sex;
    private int age;
    private String address;
    
    public User() {
    }
    public User(long id, String name, boolean sex, int age, String address) {
        super();
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.address = address;
    }
    //getter、setter
    
    @Override
    public String toString() {
        return this.id + "#" + this.name + "#" + this.age + "#" + this.sex + "#" + this.address;
    }
}

2、 对Morphia对象一些简单的使用,看看该对象提供了哪些基本的操作方法

package com.hoo.test.morphia;
 
import java.net.UnknownHostException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.EntityInterceptor;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.mapping.MappedClass;
import com.google.code.morphia.mapping.Mapper;
import com.google.code.morphia.mapping.cache.EntityCache;
import com.hoo.entity.User;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
 
/**
 * <b>function:</b> morphia对象的简单测试
 * @author hoojo
 * @createDate 2011-5-31上午11:30:20
 * @file MorphiaTest.java
 * @package com.hoo.test
 * @project Morphia
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public class MorphiaTest {
    private Mongo mongo;
    private Morphia morphia;
    
    @Before
    public void init() {
        try {
            mongo = new Mongo();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (MongoException e) {
            e.printStackTrace();
        }
        morphia = new Morphia();
    }
    
    private void print(Object o) {
        if (o != null) {
            System.out.println(o.toString());
        }
    }
    
    /**
     * <b>function:</b> morphia对象的简单测试
     * @author hoojo
     */
    @SuppressWarnings("deprecation")
    @Test
    public void testMorphia() {
        // 创建一个Datastore,过时的方法不推荐使用
        Datastore ds = morphia.createDatastore("myTestDB");
        print("createDatastore: " + ds);
        // 创建ds
        ds = morphia.createDatastore(mongo, "myTestDB");
        print("createDatastore: " + ds);
        // 创建一个带用户名、密码的ds
        //ds = morphia.createDatastore(mongo, "myTestDB", "admin", new char[] { '1', '2', '3', '4', '5', '6' });
        
        // 设置操作资源对象,这里设置User.class 就可以完成对User的一系列操作
        //morphia.map(User.class);
        //morphia.mapPackage("com.hoo.entity");//会把整个包下面的类都加载进来
        // 将对象转成DBObject
        print("toDBObject: " + morphia.toDBObject(new User(System.currentTimeMillis(), "jackson", true, 22, null)));
        // 将参数2转换成参数1的类型
        print("fromDBObject: " + morphia.fromDBObject(User.class, BasicDBObjectBuilder.start("sex", true).get()));
        print("getMapper: " + morphia.getMapper());
        print("isMapped: " + morphia.isMapped(User.class));
        
    }
    
    /**
     * <b>function:</b> 对Mapper对象相关操作
     * @author hoojo
     * @createDate 2012-2-16下午10:20:38
     */
    @Test
    public void testMapper() {
        Mapper mapper = morphia.getMapper();
        // 添加对象映射
        print("addMappedClass: " + mapper.addMappedClass(User.class));
        //print(mapper.addMappedClass(mapper.addMappedClass(User.class));
        
        // 创建实体缓存
        print("createEntityCache: " + mapper.createEntityCache());
        print(mapper.getCollectionName("myTestDB"));
        print(mapper.getConverters());
        User user = new User(System.currentTimeMillis(), "jackson", true, 22, null);
        user.setId(1306814012734L);
        print(mapper.getId(user));
        
        for (EntityInterceptor ei : mapper.getInterceptors()) {
            System.out.println("EntityInterceptor: " + ei);
        }
 
        // 查询主键
        print("getKey: " + mapper.getKey(user));
        // 所有已经映射的class
        for (MappedClass mc : mapper.getMappedClasses()) {
            System.out.println("getMappedClasses: " + mc);
        }
        
        print("mcMap: " + mapper.getMCMap());
        
        print("getOptions: " + mapper.getOptions());
        print("keyToRef: " + mapper.keyToRef(mapper.getKey(user)));
        print("refToKey: " + mapper.refToKey(mapper.keyToRef(mapper.getKey(user))));
    }
    
    /**
     * <b>function:</b> 实体缓存
     * @author hoojo
     */
    @Test
    public void testEntityCache() {
        EntityCache ec = morphia.getMapper().createEntityCache();
        print("EntityCache: " + ec);
        Datastore ds = morphia.createDatastore(mongo, "myTestDB");
        User user = new User(System.currentTimeMillis(), "jackson", true, 22, null);
        user.setId(1306814012734L);
        
        // 添加实体
        ec.putEntity(ds.getKey(user), user);
        // 代理
        ec.putProxy(ds.getKey(user), user);
        
        print("getKey: " + ds.getKey(user));
        print("getProxy: " + ec.getProxy(ds.getKey(user)));
        print("getEntity: " + ec.getEntity(ds.getKey(user)));
        
        print(ec.exists(ds.getKey(user)));
        
        print("stats: " + ec.stats());
    }
    
    @After
    public void destory() {
        mongo = null;
        morphia = null;
        System.gc();
    }
}

四、利用Morphia完成对Datastore对象的CRUD操作

1、 首先添加如下准备代码,随后的方法直接添加到该文件中即可

package com.hoo.test.ds;
 
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Key;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.query.UpdateOperations;
import com.hoo.entity.User;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
 
/**
 * <b>function:</b> Datastore增删改查操作
 * @author hoojo
 * @createDate 2011-5-31下午06:29:04
 * @fileDatastore DatastoreTest.java
 * @package com.hoo.test.ds
 * @project Morphia
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public class DatastoreTest {
    private Mongo mongo;
    private Morphia morphia;
    private Datastore ds;
    
    @Before
    public void init() {
        try {
            mongo = new Mongo();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (MongoException e) {
            e.printStackTrace();
        }
        morphia = new Morphia();
        morphia.map(User.class);
        ds = morphia.createDatastore(mongo, "temp");
    }
    
    private void print(Object o) {
        if (o != null) {
            System.out.println(o.toString());
        }
    }
    
    
    /**
    * <b>function:</b> 查询所有
    * @author hoojo
    * @createDate 2012-2-16 下午10:36:13
    */
    private void query() {
        Iterable<User> it = ds.createQuery(User.class).fetch();
        while(it.iterator().hasNext()) {
            print("fetch: " + it.iterator().next());
        }
    }
    
    @After
    public void destory() {
        mongo = null;
        morphia = null;
        ds = null;
        System.gc();
    }
}

2、 增删改CUD操作

/**
 * <b>function:</b> CUD增删改
 * @author hoojo
 * @createDate 2012-2-16 下午10:46:08
 */
@Test
public void testCUD() {
    // 添加测试数据
    for (int i = 0; i < 50; i++) {
        User u = new User(System.currentTimeMillis() + i, "test-" + i, ((i % 2 == 0)? true: false), 18 + i, "china-gz#" + i);
        print(ds.save(u));
    }
    //ds.delete(ds.createQuery(User.class));
    
    List<User> users = new ArrayList<User>();
    users.add(new User(1306907246518L, "zhangsan", true, 22, "china-gz"));
    User user = new User(System.currentTimeMillis() + 3, "zhaoliu", true, 29, "china-beijin");
    users.add(user);
    users.add(new User(System.currentTimeMillis() + 6, "wangwu", true, 24, "china-shanghai"));
    users.add(new User(System.currentTimeMillis() + 9, "lisi", true, 26, "china-wuhan"));
    //添加集合
    print("save: " + ds.save(users));
    
    //添加数组
    print("save: " + ds.save(users.toArray()));
    
    this.query();
    print("getKey: " + ds.find(User.class, "id", 1306907246518L).getKey());
    
    //修改操作
    UpdateOperations<User> uo = ds.createUpdateOperations(User.class);
    
    print("update: " + ds.update(ds.find(User.class, "id", 1306907246518L).getKey(), uo).getUpdatedCount());
    uo.add("name", "zhaoliuliu").set("age", 29).set("sex", true).add("address", "gzz");
    print("update: " + ds.update(ds.find(User.class, "id", 1306907246518L).getKey(), uo).getUpdatedCount());
 
    print("update: " + ds.update(ds.createQuery(User.class).field("id").equal(1306907246518L), uo).getUpdatedCount());
    print("update: " + ds.update(ds.find(User.class, "id", 1306907246518L), uo).getUpdatedCount());
    
    uo = ds.createUpdateOperations(User.class);
    uo.set("name", "zhaoqq").set("age", 29).set("sex", true).add("address", "fzz");
    print("update: " + ds.update(ds.find(User.class, "id", 1306907246518L).get(), uo).getUpdatedCount());
    
    print("update: " + ds.update(ds.createQuery(User.class).field("id").equal(1306907246518L), uo, true).getUpdatedCount());
    
    // 修改第一个对象
    print("updateFirst: " + ds.updateFirst(ds.createQuery(User.class).field("id").equal(1306907246518L), uo).getUpdatedCount());
    //当参数createIfMissing为true的时候,如果修改的对象不存在就会添加这条数据,如果为false的情况下,不存在也不添加
    print("updateFirst: " + ds.updateFirst(ds.createQuery(User.class).field("id").equal(1306907246519L), uo, true).getUpdatedCount());
    user.setId(1306907246518L);
    print("updateFirst: " + ds.updateFirst(ds.createQuery(User.class).field("id").equal(1306907246518L), user, true).getUpdatedCount());
    
    user.setId(1306916670518L);
    // 合并
    print("merge: " + ds.merge(user).getId());
    this.query();
    
    //删除
    print("delete: " + ds.delete(ds.createQuery(User.class).field("id").equal(1306907246518L)).getN());
    print("delete: " + ds.delete(ds.find(User.class, "age", 29).get()).getN());
    //print("delete: " + ds.delete(User.class, 1306911594631L).getN());
    //print("delete: " + ds.delete(User.class, users).getN());
    //ds.delete(ds.createQuery(User.class));
    this.query();
}

3、 Find查询操作

/**
 * <b>function:</b> find查询
 * @author hoojo
 * @createDate 2012-2-16 下午10:45:55
 */
@Test
public void testFind() {
    print("find: " + ds.find(User.class).asList());
    //like
    print("find-contains: " + ds.find(User.class).field("name").contains("test-1").asList());
    //忽略大小写
    print("find-containsIgnoreCase: " + ds.find(User.class).field("name").containsIgnoreCase("ja").asList());
    
    print("find-endsWith: " + ds.find(User.class).field("name").endsWith("22").asList());
    print("find-endsWithIgnoreCase: " + ds.find(User.class).field("name").endsWithIgnoreCase("CK").asList());
    
    //过滤null或是没有name属性的
    print("find-doesNotExist: " + ds.find(User.class).field("name").doesNotExist().asList());
    //查询name有值的数据
    print("find-doesNotExist: " + ds.find(User.class).field("name").exists().asList());
    //age > 48
    print("find-greaterThan: " + ds.find(User.class).field("age").greaterThan(66).asList());
    //age >= 48
    print("find-greaterThan: " + ds.find(User.class).field("age").greaterThanOrEq(66).asList());
    
    List<Integer> ageList = new ArrayList<Integer>(); 
    ageList.add(22);
    ageList.add(55);
    ageList.add(66);
    //all
    print("find-hasAllOf: " + ds.find(User.class).field("age").hasAllOf(ageList).asList());
    //in
    print("find-hasAnyOf: " + ds.find(User.class).field("age").hasAnyOf(ageList).asList());
    //not in
    print("find-hasNoneOf: " + ds.find(User.class).field("age").hasNoneOf(ageList).asList());
    //elemMatch
    //print("find-hasThisElement: " + ds.find(User.class).field("age").hasThisElement(55).asList());
    print("find-hasThisOne: " + ds.find(User.class).field("age").hasThisOne(55).asList());
    
    print("find-in: " + ds.find(User.class).field("age").in(ageList).asList());
    print("find-lessThan: " + ds.find(User.class).field("age").lessThan(20).asList());
    print("find-lessThanOrEq: " + ds.find(User.class).field("age").lessThanOrEq(18).asList());
    
    //print("find-lessThanOrEq: " + ds.find(User.class).field("age").near(.2, .8).asList());
    
    print("find: " + ds.find(User.class, "id", 1306813979609L).get());
    print("find: " + ds.find(User.class, "age", 28, 1, 2).asList());
    
    print("findAndDelete: " + ds.findAndDelete(ds.createQuery(User.class).field("id").equal(1306813979609L)));
    print("find: " + ds.find(User.class).asList());
}

4、 Query查询操作

/**
 * <b>function:</b> query查询
 * @author hoojo
 * @createDate 2012-2-16 下午10:40:10
 */
@Test
public void testQuery() {
    // 查询所有
    print("query: " + ds.createQuery(User.class).asList());
    // 查询主键
    print("query key: " + ds.createQuery(User.class).asKeyList());
    // 结果集数量
    print("query: " + ds.createQuery(User.class).countAll());
    // 抓取查询所有记录
    Iterable<User> it = ds.createQuery(User.class).fetch();
    while(it.iterator().hasNext()) {
        print("fetch: " + it.iterator().next());
    }
    
    // null 
    it = ds.createQuery(User.class).fetchEmptyEntities();
    while(it.iterator().hasNext()) {
        print("fetchEmptyEntities: " + it.iterator().next());
    }
    
    // all key
    Iterable<Key<User>> itkeys = ds.createQuery(User.class).fetchKeys();
    while(itkeys.iterator().hasNext()) {
        print("fetchKeys: " + itkeys.iterator().next());
    }
    
    // age > 24
    print("query: " + ds.createQuery(User.class).filter("age > ", 24).asList());
    // age in (20, 28)
    print("query: " + ds.createQuery(User.class).filter("age in ", newint[] { 20, 28 }).asList());
    
    // limit 3
    print("query: " + ds.createQuery(User.class).limit(3).asList());
    // 分页类似MySQL
    print("query: " + ds.createQuery(User.class).offset(11).limit(5).asList());
    // order排序,默认asc
    print("query: " + ds.createQuery(User.class).order("age").asList());
    //desc
    print("query: " + ds.createQuery(User.class).order("-age").asList());
    // 组合排序 order by age, name
    print("query: " + ds.createQuery(User.class).order("age, name").asList());
    
    print("query: " + ds.createQuery(User.class).queryNonPrimary().asList());
    print("query: " + ds.createQuery(User.class).queryPrimaryOnly().asList());
    //如果include 为true就表示取该属性的值,其他的默认null,反之为false则该属性为null,取其他的值
    print("query: " + ds.createQuery(User.class).retrievedFields(false, "age").asList());
}

5、 get和count查询

/**
 * <b>function:</b> get查询
 * @author hoojo
 * @createDate 2012-2-16 下午10:39:09
 */
@Test
public void testGet() {
    User user = new User();
    user.setId(1306916670518L);
    print("get: " + ds.get(user));
    List<Long> ids = new ArrayList<Long>();
    ids.add(1306907246519L);
    ids.add(1306916670524L);
    // 通过id集合查询相当于in ()
    print("get: " + ds.get(User.class, ids).asList());
    // id查询
    print("get: " + ds.get(User.class, 1306916670524L));
}
 
/**
 * <b>function:</b> count查询
 * @author hoojo
 * @createDate 2012-2-16 下午10:38:02
 */
@Test
public void testGetCount() {
    User user = new User();
    user.setId(1306916670518L);
    print("getCount: " + ds.getCount(user));
    print("getCount: " + ds.getCount(User.class));
    
    List<Long> ids = new ArrayList<Long>();
    ids.add(1306907246519L);
    ids.add(1306916670524L);
    print("getCount: " + ds.getCount(ds.get(User.class, ids)));
    
    // age > 22的记录
    print("getCount: " + ds.getCount(ds.createQuery(User.class).filter("age > ", 22)));
    // 所有
    print("countAll: " + ds.get(User.class, ids).countAll());
    print("countAll: " + ds.find(User.class).countAll());
}

6、 其他操作

@Test
public void testOthers() {
    query();
    /** 索引 */
    ds.ensureIndexes(); 
    // 同时用annotation也可以给指定的属性建立索引
    // 只需用在JavaEntity建立索引的属性上添加annotation
    /*@Indexed(value = IndexDirection.ASC, name = "address_index")
    String address;
    // 建立唯一索引
    @Indexed(value = IndexDirection.ASC, name = "bandName", unique = true)
    String name;*/
 
    ds.ensureCaps();
    User user = new User();
    user.setId(1306916670518L);
    print("getDB: " + ds.getDB());
    print("getDefaultWriteConcern: " + ds.getDefaultWriteConcern());
    print("DBColl: " + ds.getCollection(User.class)); // 查询User对象对应的集合
    Key<User> key = ds.getKey(user); // 主键
    print("getKey: " + key);
    print("exists: " + ds.exists(user)); //是否存在该对象
    print("exists: " + ds.exists(ds.getKey(user)));
    
    print("getByKey: " + ds.getByKey(User.class, key));
    List<Key<User>> keys = new ArrayList<Key<User>>();
    keys.add(key);
    user.setId(1306916670521L);
    keys.add(ds.getKey(user));
    print("getByKey: " + ds.getByKeys(keys));
    print("getByKey: " + ds.getByKeys(User.class, keys));
    
    query();
}

用Morphia操作对象相对比较简单,它对MongoDB对Java的操作进行了一些封装,特别是查询这方面的。有没有感觉像是在用Hibernate?



作者:hoojo
出处:
blog:http://blog.csdn.net/IBM_hoojo
         http://hoojo.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。


版权所有,转载请注明出处 本文出自:
分享道版权所有,欢迎转载,转载请注明出处,谢谢
posted on 2012-02-17 10:34 hoojo 阅读(2611) 评论(1)  编辑  收藏 所属分类: JavaEEOthers

评论:
# re: NoSQL 之 Morphia 操作 MongoDB 2012-02-17 13:23 | jackerxff

只有注册用户登录后才能发表评论。


网站导航: